Archive for April, 2016

Improvement on First Windows 10 IoT Core Windows Application

Now that I have a working first application working, I wanted to see how far I can take the application writing model on the Raspberry Pi.

Our first Windows application is a WPF application.  Let see if we can leverage the full power of WPF and take it to the next level.

Why

WPF application will work with hardcoded event handlers on the page. But there is a better more comprehensive way to do WPF. It’s called MVVM.

Being a purist, I would much rather do things correctly. So I want to make sure WPF for Windows 10 IoT Core applications support MVVM.

MVVM is a bit overkill for this small application. But once our applications start becoming more and more complicated, MVVM will make things a lot easier to manage.

WPF, XAML and MVVM

Before we start, note that I will not go into details here. MVVM is a much wider and complicated field than what this little blog post can answer. I’m just going to give you a quick overview and provide you with an example. If you need more information feel free to google it.

MVVM (Model, View, ViewModel) is a design pattern. One of the most powerful feature of MVVM is that it can separate the UI from the functionality. MVVM is composed of 3 different components:

  • Model: Contains the data.
  • View: Provides a screen.
  • ViewModel: Provides the functionality.

WPF is particularly well suited for the MVVM pattern.

XAML is the View language for WPF application. XAML is a declarative language that can be edited completely separate from the actual functionality code. This means that the developers can write all the functionality, and then let the designers build the screen.

What we need for MVVM under WPF is:

  • Data Binding
  • Commanding support

My take on MVVM

You will notice that we do not implement a Model. That is because there is no real data our application manages.

Let’s get started:

Utility Classes

First I need a couple of utility classes to support Data Binding and Commands.

BaseVM: Implements the INotifyPropertyChanged interface so that the functionality (ViewModel) can notify the UI that something changed. Here is the code:

public class BaseVM : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        Debug.WriteLine("OnPropertyChanged: {0}", propertyName);
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

VMCommand: Implements the ICommand interface so that the UI can send commands to the functionality (ViewModel). Here is the code:

public delegate bool CanExecuteDelegate(object o);
public delegate void ExecuteDelegate(object o);

public class VMCommand : ICommand
{
    public VMCommand(ExecuteDelegate execute)
    {
        ExecuteFunction = execute;
        CanExecuteFunction = null;
    }

    public VMCommand(ExecuteDelegate execute, CanExecuteDelegate canexec)
    {
        ExecuteFunction = execute;
        CanExecuteFunction = canexec;
    }

    private ExecuteDelegate ExecuteFunction { get; set; }
    private CanExecuteDelegate CanExecuteFunction { get; set; }

    public event EventHandler CanExecuteChanged;

    public bool CanExecute(object parameter)
    {
        bool result = true;
        if (CanExecuteFunction != null)
        {
            result = CanExecuteFunction(parameter);
        }
        return result;
    }

    public void Execute(object parameter)
    {
        if (ExecuteFunction != null)
        {
            ExecuteFunction(parameter);
        }
    }

    public void OnCanExecuteChanged()
    {
        if (CanExecuteChanged != null)
        {
            CanExecuteChanged(this, new EventArgs());
        }
    }
}

ViewModel

Then I implemented the functionality in the ViewModel. Notice that:

  • The ViewModel truly represents the business. Its public members are: GreetingMessage, PersonName and GreetCommand.
  • The code implementation for the GreetExecute function is very simple, it reads/writes properties of the ViewModel and is not aware of controls on the View

Here is the code:

public class MainPageVM : BaseVM
{
    public MainPageVM()
    {
        InitializeCommands();
    }

    private string m_GreetingMessage = "Hello World!";
    public string GreetingMessage
    {
        get
        {
            return m_GreetingMessage;
        }
        set
        {
            if(value != m_GreetingMessage)
            {
                m_GreetingMessage = value;
                OnPropertyChanged();
            }
        }
    }

    private string m_PersonName = string.Empty;
    public string PersonName
    {
        get
        {
            return m_PersonName;
        }
        set
        {
            if (value != m_PersonName)
            {
                m_PersonName = value;
                OnPropertyChanged();
            }
        }
    }

    public VMCommand GreetCommand { get; set; }
    private void InitializeCommands()
    {
        GreetCommand = new VMCommand(GreetExecute);
    }

    private void GreetExecute(object o)
    {
        string greet = "Hello World!";
        if (!string.IsNullOrEmpty(PersonName))
        {
            greet = string.Format("Hello {0}!", PersonName);
        }
        GreetingMessage = greet;
    }

}

View

Then I wrote the XAML View. Notice that:

  1. We declare a ViewModel as a resource that we instantiate as the DataContext of the top Grid. This is how we access the ViewModel.
  2. The controls do not need to be named, because they are not referenced anywhere in the code.
  3. The Text properties of controls are bound to the ViewModel members. Because the ViewModel derives from BaseVM, the content of Text will change whenever the content of the ViewModel property changes. Also when the TextBox looses focus, it will automatically update the view model.
  4. Also there is no event handler on the Button instead there is a binding to the Command on the ViewModel.

Here is the code:

<Page
    x:Class="HelloWorld.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:HelloWorld"
    xmlns:vm="using:HelloWorld.VM"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"    
    mc:Ignorable="d">
    <Page.Resources>
        <vm:MainPageVM x:Key="PageViewModel" />
    </Page.Resources>
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" DataContext="{StaticResource PageViewModel}">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="51"/>
            <RowDefinition Height="51"/>
            <RowDefinition Height="51"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <TextBlock Grid.Row="1" Text="{Binding GreetingMessage}" HorizontalAlignment="Center"/>
        <TextBox Grid.Row="2" Text="{Binding PersonName, Mode=TwoWay}" HorizontalAlignment="Center" Margin="5" Width="150"/>
        <Button Grid.Row="3" Content="Greet" Command="{Binding GreetCommand}" HorizontalAlignment="Center" />
    </Grid>
</Page>

Testing

Now that our application is written, we will build and test it. First I tested it on my local machine. Then switched to Remote Debugging to test it on the Raspberry Pi.

Conclusion

MVVM is a very powerful model for writing WPF application. I am glad to see that the Windows 10 IoT Core application can support full WPF application written in MVVM.

This means we can create much more evolved and complicated applications more easily.

, , , , ,

Leave a comment

First Windows 10 IoT Core Windows Application

So now that I have my device up and running, time to start coding. So I’ll be writing my first application.

Objectives

I could start coding a complicated app using the GPIO or talking with advanced devices using I2C. But I just wanted to see what was possible on the device first.

The objective of this first application are:

  • Creating a MINIMAL basic UI based application.
  • See if it could be deployed to the device.
  • See my application run on the Raspberry Pi.
  • Start a debugging session, place break points and watch variable values.

Getting Started

Creating a Universal Windows Project

In Visual Studio 2015, I clicked File | New Project….

FirstAppNewProject

Coding

Once the project was loaded, I opened up the main page MainPage.xaml. I created a basic layout, added a TextBlock, a TextBox and a Button. Here is the code:

XAML

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="51"/>
        <RowDefinition Height="51"/>
        <RowDefinition Height="51"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <TextBlock x:Name="textBlock" Grid.Row="1" TextWrapping="Wrap" Text="Hello World!" HorizontalAlignment="Center"/>
    <TextBox x:Name="textBox" Grid.Row="2" TextWrapping="Wrap" Text="" HorizontalAlignment="Center" Margin="5" Width="150"/>
    <Button x:Name="Greet" Content="Button" Grid.Row="3" HorizontalAlignment="Center" Click="Greet_Click"/>
</Grid>

I double clicked on the button to write an event handler. And typed in the following code:

C#

private void Greet_Click(object sender, RoutedEventArgs e)
{
    string greet = "Hello World!";
    if(!string.IsNullOrEmpty(textBox.Text))
    {
        greet = string.Format("Hello {0}!", textBox.Text);
    }
    textBlock.Text = greet;
}

Testing the application

To make sure the application was working as expected I started it from my local machine.

FirstAppStartLocal

As expected, I got a new window with the following in it:

FirstAppStart

I typed in my name, clicked the button and got:

FirstAppWorking

Fantastic! The app works! So I closed the window to stop the debug process before I continue.

Starting on the Raspberry Pi

Now that I have a working app, it’s time to try to run it on the device. To do this:

  1. Change set your debug target to Remote Machine
    FirstAppStartChange
  2. Specify the machine address
    FirstAppStartRemote
  3. Change your build target to ARM
    FirstAppStartRemoteTarget
  4. Click Remote Machine to start the debugging session

Once this is done a number of things will happen:

  1. The application will be built.
  2. If this is the first time, Visual Studio will check some of the requirements on the remote device and install missing packages.
  3. Visual Studio will deploy the application to the remote device
  4. Visual Studio will start the remote debugger for the application on the device
  5. Visual Studio start the application.

This is the build output for this process:
Output Window (Build)

1>------ Build started: Project: HelloWorld, Configuration: Debug ARM ------
1>  HelloWorld -> C:\prog\IoT\HelloWorld\HelloWorld\bin\ARM\Debug\HelloWorld.exe
2>------ Deploy started: Project: HelloWorld, Configuration: Debug ARM ------
2>Creating a new clean layout...
2>Copying files: Total 16 mb to layout...
2>Checking whether required frameworks are installed...
2>Framework: Microsoft.NET.CoreRuntime.1.0/ARM, app package version 1.0.23819.0 is not currently installed.
2>Framework: Microsoft.VCLibs.140.00.Debug/ARM, app package version 14.0.23918.0 is not currently installed.
2>Installing missing frameworks...
2>Registering the application to run from layout...
2>Deployment complete (0:01:52.439). Full package name: "ad63be4b-92ac-472f-8c68-f4537d5b5ce9_1.0.0.0_arm__7j55shkp2zhzg"
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
========== Deploy: 1 succeeded, 0 failed, 0 skipped ==========

After that the application will start on the Raspberry Pi.

Debugging

So I first tried the application on the Raspberry Pi. I typed in my name, clicked “Button” and got the expected result.

Now going back to my development machine, I place a break point in the button click event handler.

On the device I type Test in the TextBox and click “Button”.

As expected, on development machine, Visual Studio breaks on the break point. I press F10 to step through and I am debugging.

FirstAppBreakPoint

When I look at the watch I can see all the variables value:

FirstAppWatchWindow

I press F5 to resume and the application continues to run as normal.

To stop the application, you need to stop the debugging session in Visual Studio.

Conclusion

It works! I can create a XML based application and run it on my Raspberry Pi.

One thing I have noticed is that the application on the Raspberry Pi is Modal. You cannot stop the application or get out of it. This will be useful in the future.

, , , ,

Leave a comment

Re-imaging the SD Card to default

For some reason, my SD card got corrupted. I had to re-build it.

Process

The process to create new SD card for Windows 10 IoT Core is quite simple. All you need is the Windows IoT Dashboard application and an SD card (at least 8Gb is recommended).

  1. Start Windows IoT Dashboard application
    DashboardSetupNewDevice
  2. Give it a few seconds to populate Device type
  3. Select your device
  4. Insert you SD card into your computer
  5. Select your SD card in the Drive drop down list
  6. Click the “Download and install”
  7. The application will then download the image (this will take a few minutes). A progress bar is provided.
  8. Then a command line application will then write the image on the card (again this will take a few minutes). A progress bar is provided.
  9. When completed you get the following screen:
    DashboardSDFlashComplete
  10. Once your device is booted up, you should see it in the My device.

Conclusion

Re-imaging an SD is an easy strait forward process. It takes only 5-10 minutes and you get a brand new device.

You will loose any changes or information stored on your card. So you will have to re-configure it after.

, , ,

Leave a comment

Windows Updates Issues

I’ve had somewhat of an adventure with the Windows Update process on the Windows 10 IoT  Core.

Updating Windows

In the Windows Device Portal I was on the Windows Update page. So to make sure my device was up to date, I clicked the “Check for updates” button and … nothing happened on screen. Knowing that the process was probably running in the background, I moved on to check other pages.

When I came back to that screen later I got a You must restart your device to apply the updates kind of button. So I clicked on it and the device proceeded to reboot as expected. I got the cog wheel going and a progress bar for a number of minutes. Then I got a giant frown emoticon:

GiantFrown

And the screen went blank. I waited for 30 minutes then turned off the device. Then turned it back on, got cog wheels for a few minutes, then frown, then blank. It had essentially screwed up the Operating System.

Flashing the SD card

I took out my SD card, placed it in my development machine. And proceeded to re-image it without issues. Placed the card back in my device and it started without issues.

In any case, it gave me the material to write a post about Flashing the SD card…

Conclusion

This happened to me on a brand new device with a new SD card that is part of a starter pack.

This may have been a bad fluke. But getting errors like this on a clean device is a bit worrisome.

, ,

Leave a comment

Getting Started with Raspberry Pi

So I finally got the Raspberry Pi hardware yesterday. I will spare you the unboxing video, I’m sure there are a number of them already.

I plugged in the Raspberry Pi to a keyboard, a mouse, and a screen. Added the Wifi USB dongle and started it up.

This blog explores the different ways we can access the device by default. This is only an introduction, we probably will return to see some of those interfaces in more depth as we need them in the future.

Raspberry Pi on screen Experience

(Sorry, I have not figured out how to take screen shots on the Raspberry Pi yet, and phone picture are horrible. I will add screen shots when/if I figure it out)

First Start Up

After churning for a couple minutes, it prompted me for language and selecting the wireless network. That done, it re-directed me to the main screen.

If you saved the default settings, on subsequent start ups, the boot process sends you directly to the main screen.

Main Screen

On the main screen, the device information application is displayed. The top of the screen look like a task bar with applications running on the left with a system tray to the right.

The applications running are:

  • Device info
  • Tutorials

The system tray has:

  • Time
  • Device Settings
  • On/Off button

The On/Off button offers:

  • Shutdown
  • Restart

Device Settings Page

The Device Settings page allows you to set:

  • Basic preferences: Only sets language at this point
  • Network & Wi-Fi: Select and configure Wi-Fi

Windows 10 IoT Core Dashboard

Going back to my development computer and I fired up the Windows 10 IoT Core Dashboard to see what would show up.

Start up

The startup page gets you on the Set up a new device. Setting up a new device is used to create a new SD card. I already had a pre-configured SD card (from the starting pack) so I went directly to My devices.Dashboard1

Device List

My devices show a list of devices connected on your network. Give it a few minutes to detect your device.

Dashboard2

From here you can open up the device Settings or Open in Device Portal. I went for Settings.

Device Settings

The Device Settings page allows you to change your device name and set your administrator password. You should take the time to at least change the password. The default password for the Administrator account is: p@ssw0rd

Dashboard3

From here we’ll go to the Windows Device Portal in browser.

Windows Device Portal

The Windows Device Portal is a web page served directly by the device. It provides a lot more functionality than the IoT dashboard or the device interactive UI. The left hand menu allows you to navigate to different sections. PortalMenu

The sections are:

  • Home
  • Apps
  • Processes
  • Performance
  • Debugging
  • ETW
  • Perf Tracing
  • Devices
  • Bluetooth
  • Audio
  • Networking
  • Windows Update

Also a number of functions are available on the right hand header:

PortalFunctions

Here are the more high level and useful pages for now:

Home

The home page provides information about the device, allows you to change the device name and change the administrator password.

PortalHome

App Manager

The App Manager page provides a lot of functionality. It allows you to manage applications, uninstall application, select default startup application. It also allows you to deploy new applications.

PortalApps

Debug

The debugging page provides a list of the current processes, displays error logs and set error reporting parameters. It also allows you to manually start the Visual Studio Remote Debugger.

PortalDebug

Note: The remote debugger is not installed by default on Windows IoT Core 10586. It is only deployed the first time you start a debugging session from Visual Studio. If you attempt to start the Remote Debugger before you start a debugging session, you get the following error message is:

PortalDebugError

Networking

The networking section allows you to set the networking parameters. It provides a list of available networks and displace the current IP configuration for the different networking interfaces on the device (I snipped the screen shot, it actually showed 3 network adapters).

PortalNetwork

 

Updates

The Windows Update page allows you to check for available operating system updates. If updates are available they will be installed on the next restart.

Note: See my next post before clicking this button

PortalUpdate

Conclusion

This seems to be most of the out of the box high level user interfaces available to interact with the Windows 10 IoT Core operating system.

Of course there are also more advanced mode of interaction available like command lines, PowerShell and programming APIs. But we will see those in other posts in the future.

 

 

 

, , ,

Leave a comment

Anatomy of GPIO on Windows IoT

Let’s explore the General Purpose Input/Output (GPIO) interface offered by the Windows 10 IoT core.

The GPIO interface is deceptively simple. It consists in a few classes and enumerations. The main classes are:

  • GpioController class: Provides access to all the pins of the GPIO(s) bus.
  • GpioPin class: Represents a single pin on the GPIO. It provides functions to read/write pin values and provides an event that can be triggered when a pin value changes.

GpioController

The GpioController class cannot be directly instantiated. Instances are accessed through one of the static functions on the class:

  • GetDefault(): Returns the default Gpio controller for the device.
  • GetDefaultAsync(): Returns the default Gpio controller for the device asynchronously.
  • GetControllersAsync() : Returns a list of all the Gpio controllers available for the device asynchronously.

The instance functions of the GpioController are used to manage pins:

  • PinCount: Returns the number of pins available for this GpioController.
  • OpenPin(): Opens a connection to the pin and returns the corresponding GpioPin. An overload of the function allows you to supply a sharing mode other than exclusive.
  • TryOpenPin(): Opens a connection to the pin and returns the corresponding GpioPin. This variant will not throw an exception on error but will return a status making it easier to handle errors.

GpioPin

The GpioPin class gives you access to read and manipulate a single pin. Like the GpioController, you cannot instantiate this class directly. You access it using the GpioController OpenPin or TryOpenPin functions.

The GpioPin class provides members query information about the pin:

  • PinNumber: Returns the pin number for this pin.
  • SharingMode: Returns the sharing mode for this pin. Modes can be Exclusive or SharedReadOnly.

The GpioPin class provides members configure the pin. Drive mode is probably the most important item to configure on a pin. It tells the pin whether it is an input or an output and specifies the way the electronic is organized. There are multiple drive mode available see GpioPinDriveMode for more information about the available drive modes. I will do a post specific to this later on.

  • IsDriveModeSupported(): Can the pin support this drive mode.
  • GetDriveMode(): Returns the currently configured drive mode for this pin.
  • SetDriveMode(): Sets the drive mode for this pin.
  • ValueChanged: Event that is triggered when a change of state is detected on the pin. This member allows us to attach an event handler to handle that event.
  • DebounceTimeout: Get/Sets the interval of time after the ValueChanged event is trigger during which the changes in the pin will not trigger another ValueChanged event.

The GpioPin class provides members to read and write the value of the pin:

  • Read(): Returns the current value of the pin High/Low. This will work on inputs or output pins.
  • Write(): Sets the value for the pin High/Low. This will only work on output pins.

Usage

There are a number of possible ways to use the GPIO. The most common scenario are:

Pin reading / writing

This process consist in setting up your pin(s), manipulating them and disposing of the pin when done.

GPIO-Manipulation-Activity

Reading and Writing GPIO Pins

 

Monitoring Events

This process consist in setting up your pin(s), registering an event handler that will be triggered when a pin change is detected and waiting for events to occur, and disposing of the pin(s) when done .

GPIO-EventBased-Activity

Reading and Writing GPIO Pins

 

Conclusion

The GPIO interface provided by the Windows 10 IoT library is simple but comprehensive. This information should allow us to come up with a plan on how to write device code.

The only touchy points I can see so far is: Figuring out how to set a valid DebounceTimeout value. We’ll be in a better position to figure out those details once we start coding against an actual device.

For more information see the MSDN documentation

https://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.gpio.gpiocontroller.aspx

, ,

Leave a comment

Windows IoT Core – First Impressions

Now that my development computer is setup, I wanted to look at some code. So I explored a little around the start up sample projects offered by Adafruit where I purchased the Microsoft IoT Pack for Raspberry Pi 2. I also looked at Microsoft supplied samples and the Raspberry Pi Foundation web site.

My goal here was: To look at code to understand the general anatomy of the process to develop IoT devices using the Raspberry Pi. To see someone using the GPOI in C#.

Dice Application

I found tons of good projects of all kind. I just wanted one that would be simple, but would give me an overall view. The one offered by Adafruit offered all the information I wanted:

https://blogs.technet.microsoft.com/uktechnet/2015/10/23/creating-a-simple-windows-10-iot-application-led-dice/

This blog post clarified a number of points for me:

Windows Universal Application

Visual Studio offers a large amount project templates. Choosing the right template can mean the difference between success and re-doing everything. Unfortunately for me, having done mostly ASP.NET and MVC (with some WPF) applications for the past 15 years, I was not aware of the Windows Universal application thread.

I had already started coding some useful libraries that I wanted to re-use across multiple project types. I used the Portable Libraries project type for those. Of course, I could just copy/paste the code into a Windows Universal class library but that defeats the purpose of re-use… Some re-design will be required there for sure.

WPF User Interface on the Device

I did not expect this and I did not expect it would be this easy. You can write the User Interface for your application to run directly on the device.

Best of all it’s WPF and I am quite comfortable with it. I see great things happening in this department!

Coding the GPIO

Although the code in this application is very linear and repetitive (for simplicity purpose I am sure), it shows that the code to access and control the GPIO is simple. I did some additional research and figured out that: Yeah! This is actually really simple!

Building Electronic Circuit

Last time I wrote an electronic circuit was in 1992. I do have a lot updating to do. The section “Building out the circuit” in this sample was just what I needed to get me thinking about this again.

Perhaps the most interesting thing here is Fritzing . Fritzing is an application to create and document your electronic circuit prototype. That is definitely something I will have to explore deeper.

Running and Debugging

There is no talk about debugging, but running seems quite easy and strait forward. Just start the application on the device, provide device IP address and Voila!

Conclusion

I feel quite confident we can get this working and have fun doing it. This is going to be a lot easier than I expected!

 

 

, ,

Leave a comment