Welcome to MSDN Blogs Sign in | Join | Help

.NET Micro Framework : .NET Micro Framework 4.0 Goes to Beta!!!

The .NET Micro Framework V4.0 has gone into public beta. Congrats to the team for all the hard work getting this done with reduced resources and an uphill legal battle on the source code release!

.NET Micro Framework : .NET Micro Framework 4.0 Goes to Beta!!!

.NET Micro Framework V4.0 Beta

The .NET V4.0 Beta is coming to a PC near you. Sign up on Microsoft Connect to get your copy when it becomes available!n Lot’s of great new features and SOURCE CODE in this release!

Download details: .NET MF Port Kit

In case you hadn’t noticed or seen it. The .NET Micro Framework Porting Kit V3.0 is now freely available on MS downloads. This isn’t a new version, it’s the same one we released in 3Q08. It’s just a free download now. Work is progressing on the next version so stay tuned

Download details: .NET MF Port Kit

Posted by smaillet | 2 Comments

Strange days are these…

As many readers know (Wait, is there really more than one?) by now my position on the .NET Micro framework team was eliminated. I was given 60 days to find a job within Microsoft before termination and severance kicked in on July 4th. Last week I started to write a farewell as my final post. However, I had one final interview loop to go, so I held off… Apparently somebody liked me in this interview as I got the job! I’ve moved to the Windows Embedded team as a developer. (I can’t say much about it at this point as we’re working on some new stuff and I’m not entirely clear on what’s public info or not but as things go public I’ll be sure to blog about it!) I officially started on Thursday last week so things switched pretty quickly.

While I won’t be abandoning the .NET MF, I’ll shift my blogging to a larger embedded products focus depending on my current whims. I will follow through and finish on the KIOSK emulator and basic demo app code. I’ll also probably spend some time dissecting the FusionWare::DFX (Driver Framework for windows CE). Since it is publicly available in source code form I can make a change or two to increase the overall efficiency of the system that was more difficult to do when it was something we tried to protect as “IP”.

-Steve

Posted by smaillet | 0 Comments

Colin has posted a clarification of rumors

Please see Colin’s post for official word on rumors about the demise of .NET Micro Framework. (Hint: he’s NOT dead Jim!)

http://blogs.msdn.com/netmfteam/archive/2009/05/07/net-mf-moves-to-developer-division.aspx

Building a WPF Emulator Part V

In our last episode the super hero(ok it was just me) was creating a device emulator for a KIOSK system based on the .NET Micro Framework. So far we’ve seen the application code from the custom emulator side of things but haven’t looked at any of the XAML yet. So what is this XAML stuff anyway? XAML is an XML language (Xml Application Markup Language) for describing hierarchies of components. In WPF those components are .NET classes. Instead of writing a lot of code to initialize and set up the UI for an application you can declare it in XAML. XAML was designed alongside of the Windows Presentation Framework (WPF) but the two are technically orthogonal. (This was a big surprise to me when I first started digging into WPF, the appendix on XAML in Chris Sells and Ian Griffith’s excellent book Programming WPF was a real eye opener on that.)

The application XAML file is one of the first you see for the KIOSK emulator it looks like this:

<Application
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 
    xmlns:app="clr-namespace:KioskEmulator"
    x:Class="KioskEmulator.App"
    StartupUri="UI\MainWindow.xaml"
>
    <Application.Resources>
    </Application.Resources>
</Application>

The most important items of note for the application XAML in this sample are the StartupUri attribute that specifies the starting XAML window and the x:Class attribute which specifies the name of a class to generate for this application. Ultimately this XAML description generates a C# class that contains the basic application init. The generated code for that looks like this:

    public partial class App : System.Windows.Application {
 
        /// <summary>
        /// InitializeComponent
        /// </summary>
        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public void InitializeComponent() {
 
            #line 5 "..\..\App.xaml"
            this.StartupUri = new System.Uri("UI\\EngMainWindow.xaml"
                                            , System.UriKind.Relative);
 
            #line default
            #line hidden
        }
 
        /// <summary>
        /// Application Entry Point.
        /// </summary>
        [System.STAThreadAttribute()]
        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public static void Main() {
            KioskEmulator.App app = new KioskEmulator.App();
            app.InitializeComponent();
            app.Run();
        }
    }
Ahhhh – there’s Main()! Note that the class is declared as partial so that’s how it relates to the App code I showed in Part II of this series.

The App class from Part II contained a bit of application specific startup logic that is necessary for the application to function. Based on how things are often done with Windows Forms (and our sample emulators based on it) you’d expect that the code for the main window class of the emulator would have a lot of application specific stuff in it. But, as you probably guessed by how I point that out – you’d be wrong! Here’s what the main window class code looks like:

using System.Windows;
 
namespace KioskEmulator
{
    /// <summary>
    /// Interaction logic for EngMainWindow.xaml
    /// </summary>
    public partial class EngMainWindow : Window
    {
        public EngMainWindow( )
        {
            InitializeComponent( );
        }
    }
}

Honestly, that’s it - nothing more! This is one of those blow your mind / pull the rug out from under you kind of things when you first encounter it. (at least for me it was – what, wait no Onclick handlers, no Onbutton pressed handlers - what’s going on?) This is the true beauty of XAML and WPF and the Model View + View Model (MV+VM) design pattern.  There is no business logic in the UI – not a thing. Any code that is needed in the window class is entirely related to the UI. (We’ll see in a later post that the nicer looking designer version needs a little bit of code.) Once you get your head around this idea you’ll really start to love the WPF.

Of course the natural question from this new model is: If there’s no business logic in the window code how does the application work? Well that’s the job of data binding and the ViewModel as part of the MV+VM pattern. To help get a handle on that here’s the XAML for the main window (the engineers ugly version) [ NOTE: to keep things simple and focused I’ve removed the elements and attributes that are not relevant to understanding the connection to the ViewModel ] :

<Window x:Class="KioskEmulator.EngMainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:em="http://microsoft.com/MicroFramework/Emulator"
    xmlns:app="clr-namespace:KioskEmulator"
    Title="Kiosk Emulator"
  >
  <Canvas Height="367" Width="420">
    <Image em:TouchBehavior.TouchPort="{Binding TouchPort}"
           Source="{Binding LcdImage}"
    />
    <Button em:ButtonPressBehavior.ChangedCommand="{Binding SetPinStateCommand}"
            em:ButtonPressBehavior.PinName="Select"
            em:ButtonPressBehavior.PropertyName="IsPressed"
    >Select</Button>
    <Label app:DropCardBehavior.DropCardCommand="{Binding DropNfcCard}"
           app:DropCardBehavior.ReaderType="NfcCard"
  >Nfc Reader</Label>
    <Label app:DropCardBehavior.DropCardCommand="{Binding DropMagCard}"
           app:DropCardBehavior.ReaderType="MagCard"
    >MagStrip</Label>
    <ToggleButton IsChecked="{Binding LED1,Mode=OneWay}">LED1</ToggleButton>
    <ToggleButton IsChecked="{Binding LED2,Mode=OneWay}">LED2</ToggleButton>
    <ToggleButton IsChecked="{Binding LED3,Mode=OneWay}">LED3</ToggleButton> 
    <ToggleButton IsChecked="{Binding RFIDLED,Mode=OneWay}">RFIDLED</ToggleButton>
  </Canvas>
</Window>

At the top I’ve added a couple extra namespace entries to reference the WPF emulator standard behaviors and a custom application one to access the drag and drop support for the card readers. The engineers design uses a canvas as the primary UI element container. This is usually not the best idea for production UI but is a simple way for a dev to get something going for basic testing. Inside the canvas is an image control. The first thing to notice about the image control is that it has the em:TouchBehavior.TouchPort="{Binding TouchPort}" attribute. This uses an attached property to create an attached behavior for touch support and binds it to a property on the ViewModel called TouchPort. ok, I can hear some readers thinking – “ok, right – huh?”. (Bet you didn’t know I could read minds through this here interweb thingy didya?) What that means is that we can define behavior for a UI Element independent of the actual element itself and then re-use it wherever we need to. Thus we can attach the TouchBehavior.TouchPort property to any UIElement and bind that property to a TouchPort in the Viewmodel and things get automatically hooked up. If the view model is derived from the EmulatorViewModel (part of my custom WPF emulator assembly) then all the work is done. The emulator View model will receive commands from the attached touch behavior and send it on to the emulator engine! So with the new WPF emulator library adding touch is as simple as one attribute on any UIElement in XAML – That’s what I call cool!. [Uh-oh, nerd alert!]

For the KIOSK the touch support is attached to an Image for the LCD, getting the LCD updates is also just a matter of setting up the data binding for the Image’s Source property to the ViewModel’s LcdImage property.

While the Kiosk hardware doesn’t have any buttons, it only has the LCD and touch panel, it was useful to run basic sample touch applications on the emulator as I was building up the WPF library to verify things worked. Thus the engineers view has the Select button in there. The button is using the ButtonPressBehavior, which has three attached properties. The first is a data bound command SetPinStateCommand, which comes from the general EmulatorViewModel, to change the state of a GPIO pin in the emulator based on a change in state of a boolean property. The PinName is the name used to register the Pin in the emulator class. Using a name helps keep things cleaner and allows for pin remapping in hardware revisions to impact only one place in the code. The third property is the Property name of the control that will trigger a change in the state. In this case we want to change the state of the pin with the state of the IsPressed property of the button class. Unfortunately the IsPressed property is not one that the Button class implementation will allow you to data bind directly to. Which is what drove the need for the ButtonPressBehavior.

The MagStrip and NFC Readers required drag and drop capabilities to be able to drag a data file onto the emulator to simulate swiping/tapping a card. Since a card could have both NFC and magstrip data I created a single application specific behavior for that and attached it to the label controls and data bind it to a command provided by the ViewModel. The ReaderType Property determines which type of card the reader supports so that the drag and drop behavior will show a proper icon as a file is dragged over the NFC or magstrip areas. (e.g. if you drag a card file with magstrip only data over the NFC area it should indicate you can’t drop that file on the NFC reader.)

The KIOSK Device has 3 LEDs that I emulated using a standard ToggleButton control (like a radio button without the “select only one of many” behavior). I use data binding to bind the IsChecked property of the button to the led property of the ViewModel. However, since the LED is an output it is read only on the ViewModel and therefore must be specified as OneWay binding. Otherwise, WPF will try to connect up to the property set method so that whenever the IsChecked property changes (say from clicking on the button) then the ViewModel is updated. That will generate an exception since the setter method doesn’t exist.

The really amazing thing about all this data binding and attached properties for behaviors is that it is completely re-usable without altering the ViewModel itself. The UI can be literally anything a designer can dream up and represent in XAML and the rest of the code doesn’t need to care one teensy little bit. Even better is that there doesn’t even need to be any UI!? Yep, you read that correctly - you can make unit testing or automated tests of all your core logic by exercising the ViewModel directly in the same way that the XAML windows would do. This is a big benefit to automated testing as it is more easily automated then GUI UI testing.

OK, that’s a lot to absorb, especially for us “old dogs”. I’ll leave things for the moment so there aren’t any heads exploding. Next post I’ll dig into the whole view model and data binding in more details along with the View model support classes.

GHI releases updated firmware for Embedded Master

GHI has released updated firmware for the Embedded Master module. New features include:

Version 1.0.7

04/29/2009

Firmware Version 03.00.000
Tiny Booter Version 03.00.000
> Includes .Net Micro Framework V3.0 Service Pack 1
> TinyBooter is defaulted to USB
> User can access Ethernet registers now
> Custom PPP communication interface support
> In-Field update support
> USB Host to Serial Sierra C885, 3G Modem
> Battery RAM Support
> Reboot support
> RawUSBDevice descriptor parsing enhancement
> Managed code protection support
> New Bootloader on USBizi products. Supports managed application update and protection.

.NET Micro Framework Porting kit is now available in MSDN subscriptions

Yesterday the .NET MF team announced that the .NET Micro Framework will be available in the MSDN subscriptions starting with the OS level subscription. This is great news as MSDN is already available in many distribution outlets world wide. With the recent addition of the Windows Embedded Family of products into MSDN you can get all your development tools for sensors to servers in one subscription.

Building a WPF Emulator Part IV

Part IV? already… this is starting to get like one of those scary movies series of the late 70’s and early 80’s… or Star Trek movies… (Hopefully the even numbered and the odd numbered posts are good!)

So far I’ve covered the code from the viewpoint of a custom emulator using the additional support classes I’ve created. Now it’s time to have a look at what’s going on behind the curtain of the Emulator2 class. In trying to support WPF I wanted to leverage the MVVM pattern to isolate the UI from the core of the application code. This meant either re-writing the emulator engine to support data binding or to put all the Data Binding in the ViewModel. The MVVM pattern was developed assuming a model that was unchangeable and the ViewModel wraps the model class with support for data binding and commands for the UI to use. (Kind of like an instance of the “Adapter” pattern). So I created a common ViewModel class for emulators that custom emulators cad derive from. In the process of getting that sorted out I realized it wasn’t going to be enough. The emulator uses a multi-stage initialization process and some parts of the emulator are only valid after a given stage of init , while others are only valid in the early configuration stage. I needed a way to have the ViewModel interact with the engine (running on a different thread) to complete the initialization of the UI binding at the correct stage of initialization. The solution was to create a new class (Emulator2) derived from the standard emulator class and add a set of events for the important stages of initialization. The class looks like this:

    /// <summary>Extension of standard Emulator to provide events for key state changes</summary>
    /// <remarks>The standard <see cref="emulator" /> and derived classes go through
    /// several stages of initialization. However, external classes, like a view model
    /// don't get to participate in the "notification" of state changes. Thus it is difficult
    /// for a view model to know when it is safe to attach to the emulators LCD changed event.
    /// <para>This class is designed to add events to the standard emulator for the Initialize
    /// and Uninitialize states and to simplify registration of GPIO pins and LCD display components</para>
    /// </remarks>
    public class Emulator2 : Emulator
    {
        /// <summary>Creates a new instance of an <see cref="Emulator2"/></summary>
        public Emulator2( )
        {
        }
 
        /// <summary>Creates a new instance of an <see cref="Emulator2"/></summary>
        /// <param name="Hal">Custom emulator HAL built from the .NET Micro Framework Porting kit</param>
        /// <remarks>
        /// This overload of the constructor allows setting the HAL/CLR implementation for the emulator.
        /// You can create custom HAL/CLR configurations using the .NET Micro Framework Porting kit.
        /// </remarks>
        public Emulator2(IEmulator Hal)
            : base( Hal )
        {
        }
 
        #region Emulator Thread
        /// <summary>Start the emulator engine on a new thread</summary>
        /// <remarks>Uses Environment.GetCommandLineArguments()</remarks>
        public void StartEmulator( )
        {
            new Thread( Start ).Start( );
        }
 
        /// <summary>Start the emulator engine on a new thread</summary>
        /// <param name="Args">Command line arguments</param>
        public void StartEmulator( string[ ] Args )
        {
            new Thread( Start ).Start( Args );
        }
        #endregion
 
        #region Events
        /// <summary>Event raised when the emulator has reached the Initialize state</summary>
        /// <remarks>
        /// This event is raised after the emulator is initialized but before it begins executing
        /// code. All of the EmulatorComponentCollections are fully wired up at this point. This
        /// event is normally used to trigger application code to attach to events fired by the
        /// other emulator components, such as the LCD or a GPIO pin.
        /// </remarks>
        public event EventHandler Initialize = delegate { };
 
        /// <summary>Event raised when the emulator is shutting down</summary>
        /// <remarks>
        /// This event indicates the emulator is shutting down and receivers should
        /// detach events and handle any other cleanup work needed.
        /// </remarks>
        public event EventHandler Uninitialize = delegate { };
 
        /// <summary>Triggers the <see cref="Initialize"/> event</summary>
        public override void InitializeComponent( )
        {
            base.InitializeComponent( );
            Initialize(this, null);
        }
 
        /// <summary>Triggers the <see cref="Uninitialize"/> event</summary>
        public override void UninitializeComponent()
        {
            base.UninitializeComponent( );
            Uninitialize( this, null );
        }
        #endregion
 
+ LCD/Touch
 
+ GPIO Pins 
 
    }

There’s more to it than shown here (I’ll show the LCD/Touch and GPIO Pins details in a bit) The constructors mirror that of the base class so that it works just like the original. There’s a pair of StartEmulator() methods that mirror the base class Start() method but start the emulator in a new thread. This is needed since the UI will run on the applications main thread. The events needed are Initialize and Uninitialize. Initialize is fired after everything is done just before the emulator starts processing IL instructions for the emulated application. At this point all of the Emulator Components are created and valid as are the various component collections, such as the GPIO ports, SPI bus and I2C Bus devices, etc… Thus if the ViewModel needs to connect to events or data from those components it is safe to do so when this event is fired. This covers the primary reason for the existence of the Emulator2 class. Since I had it I decided it was worth adding some more useful component registration “helpers” to handle some of the repetitive grunt work of registering components.

The first set of component registration helpers we’ll look at is the LCD/Touch support. The code looks like this:

        #region LCD/Touch
        /// <summary>Touch GPIO port for this emulator</summary>
        /// <remarks>
        /// This is normally set via a call to <see cref="RegisterLCD"/> in an override
        /// of the <see cref="LoadDefaultComponents"/> method. The UI must call the methods
        /// of the TouchGpioPort in order to generate touch events for the emulated system.
        /// </remarks>
        public TouchGpioPort TouchPort { get; protected set; }
 
        /// <summary>Registers an LCD component in the system</summary>
        /// <param name="PixelWidth">Width, in pixels, for the LCD</param>
        /// <param name="PixelHeight">Height, in pixels, for the LCD</param>
        /// <param name="Bpp">Bits per pixel setting for the LCD</param>
        /// <param name="TouchPin">Touch IRQ pin for touch support or GPIO_NONE</param>
        /// <remarks>
        /// Creates and registers an LCD Display emulator component. If TouchPin is a
        /// valid GPIO pin value <see cref="TouchPort"/> is created and registered to
        /// enable touch capabilities. 
        /// </para>NOTE: This should only be called from an overload of the
        /// <see cref="LoadDefaultComponents()"/> Method</para>
        /// </remarks>
        protected void RegisterLcd( int PixelWidth, int PixelHeight, int Bpp, Cpu.Pin TouchPin )
        {
            if( this.State != EmulatorState.Configuration )
                throw new InvalidOperationException("Cannot register LCDs unless emulator is in the Configuration state" );
 
            LcdDisplay lcd = new LcdDisplay( );
            lcd.Width = PixelWidth;
            lcd.Height = PixelHeight;
            lcd.BitsPerPixel = Bpp;
            RegisterComponent( lcd );
 
            if( TouchPin != Cpu.Pin.GPIO_NONE )
            {
                this.TouchPort = new TouchGpioPort( TouchPin );
                RegisterComponent( this.TouchPort );
            }
        }
        #endregion

Component registration can only occur in the configuration state so this should be called from an overload of the LoadDefaultComponents method. The Touch port is exposed from the emulator engine so that the ViewModel can generate touch input to the emulation engine. (We’ll look into the whole View model thing in more detail in a later post.) This method just creates and registers a new LCD component and if a TouchPin is provided it creates and registers the touch port as well.

Registering GPIO ports is also covered in the Emulator2 helpers. There are 3 overloads of the RegisterPin() method for various uses in an emulated device.

 

        #region GPIO Pins
        /// <summary>Registers a GPIO pin in the system</summary>
        /// <param name="Pin">Pin number</param>
        /// <param name="Name">Name for the pin</param>
        /// <remarks>
        /// <para>Useful method for registering a pin</para>
        /// </para>NOTE: This should only be called from an overload of the
        /// <see cref="LoadDefaultComponents()"/> Method</para>
        /// </remarks>
        protected GpioPort RegisterPin( string Name, Cpu.Pin Pin )
        {
            return RegisterPin( Name, Pin, GpioPortMode.InputOutputPort, GpioPortMode.InputOutputPort );
        }
 
        /// <summary>Registers a GPIO pin in the system</summary>
        /// <param name="Pin">Pin number</param>
        /// <param name="Name">Name for the pin</param>
        /// <param name="Key">Virtual Key to attach to the pin</param>
        /// <remarks>
        /// <para>Useful method for registering a pin that acts as a button</para>
        /// </para>NOTE: This should only be called from an overload of the
        /// <see cref="LoadDefaultComponents()"/> Method</para>
        /// </remarks>
        protected GpioPort RegisterPin(string Name, Cpu.Pin Pin, VirtualKey Key)
        {
            GpioPort retVal = RegisterPin( Name, Pin );
            retVal.VirtualKey = Key;
            return retVal;
        }
 
        /// <summary>Registers a GPIO pin in the system</summary>
        /// <param name="Name">Name for the pin</param>
        /// <param name="Pin">Pin number</param>
        /// <param name="ExpectedMode">Expected mode for the pin</param>
        /// <param name="AllowedMode">Allowed modes for the pin</param>
        /// <remarks>
        /// <para>Useful method for registering a pin</para>
        /// </para>NOTE: This should only be called from an overload of the
        /// <see cref="LoadDefaultComponents()"/> Method</para>
        /// </remarks>
        protected GpioPort RegisterPin( string Name, Cpu.Pin Pin, GpioPortMode ExpectedMode, GpioPortMode AllowedMode )
        {
            if( this.State != EmulatorState.Configuration )
                throw new InvalidOperationException(
                             "Cannot register GPIO Pins unless emulator is in the Configuration state" );
 
            GpioPort port = new GpioPort( );
            port.Pin = Pin;
            port.ModesAllowed = AllowedMode;
            port.ModesExpected = ExpectedMode;
            port.ComponentId = Name;
            RegisterComponent( port );
            return port;
        }
        #endregion

These methods are pretty straight forward and simplify some of the more tedious coding needed for registering pins.

So there’s the whole Emulator2 class with events, LCD, Touch and GPIO pin registration helper methods. Next post we’ll look at the XAML code for the engineers view and see how that ties back to the data binding in the ViewModel, then we’ll hit the ViewMode that acts as the glue to bring the XAML UI and the underlying engine together. “Tune in next week, same Bat time, same Bat channel…”

Posted by smaillet | 0 Comments

TAHOE/Meridian firmware updates and a New .NET Micro Framework Rapid Prototyping system

Device Solutions just released new Tahoe II firmware and an updated SDK. In the documentation is a section on the new Meridian/P module. (No info available on their website yet though) This is looking really cool! The direct support for SchmartBoard format makes it extremely easy to use for rapid prototyping and hobby projects!

From the docs:

Meridian/P Micro Development Board

The Meridian/P (/P for Prototype) Micro Development Board contains all the functionality of the Meridian CPU, but in a prototype-friendly format.

It incorporates a Freescale i.MXS ARM920T based processor, 8Mbytes of SDRAM, 4Mbytes of flash memory, along with an LCD controller, USB function, GPIO, SPI bus, I2C bus and serial ports. The I/O pins are all available through 0.1" headers. These have not been populated to allow you to mount them on the top or bottom of the board. Two of the expansion connectors are identical to the Tahoe-II expansion connectors, allowing Ethernet and future expansion boards to be used on the Meridian/P.

The Meridian/P form-factor fits with the SchmartBoard system. Schmartboards provide a quick and easy way to solder surface mount components, including fine pitch QFPs and BGAs.  For more information see www.schmartboard.com

The Meridian/P Technical Reference Manual includes everything you need to know about the hardware and expansion connectors.  There is also a summary of the expansion connectors [in the documentation].

Product Features

  • i.MXS + Memory  The Meridian/P features the same core components as the Meridian CPU.

  • USB Function for Power and Download/Debug

  • RS232 Serial Port The Meridian/P has a RS232 level serial port available on the J2 header.  A further serial port is available on EXP1.

  • Expansion Connectors Meridian/P includes 4 x 0.1" headers.  Two of these (EXP1 and EXP2) are identical to the expansion connectors found on Tahoe-II, allowing you use expansion boards on both platforms.  All headers are on a 0.1" grid.

  • User LED and Switch See the Getting Started Guide for an application that uses these features.

Updated interop article

I've updated the interop article to correct a few typos and reformat to fit in this blog. (unfortunately when we re-worked the layout of the team blog site the article didn't quite fit right so I adjusted it a bit and am now hosting the full article on this blog where it fits ok)

.NET Micro Framework Porting Kit SP1 released!

Last night, we released Service Pack 1 for the .NET Micro Framework Porting Kit. This release was created expressly to respond to the needs of our customers, incorporating requests submitted to us from our porting customers.

The service pack contains dozens of improvements spanning a broad range of functionality: power management, file system, cryptography, sample driver source code, and more.

Existing Porting Kit users can download SP1 from Microsoft Downloads. (NOTE: an existing 3.0 porting kit installation is required as the SP1 installation only contains the updated files.)

SO what are you waiting for, download SP1 now and get crackin’! 8^)

Building a WPF Emulator Part III

OK, so I promised we’d look at the emulator engine in this post. The design idea for the emulator places all of the device specific configuration of the emulation in code. This is in contrast to the default  “generic” Microsoft Emulator that ships with the SDK, which is configured by XML files. That’s OK for a basic general solution but leads to confusion and problems when emulating a specific set of hardware. What happens if a user deletes or edits the XML configuration file? Thus, for emulating a real device I recommend that all configuration is provided in the code instead of using the configuration files. (It’s also easier to do, especially with the support framework classes I’ve put together for this series of posts).

In the case of the KIOSK there are a number of hardware specific aspects that need to be accounted for. There are 3 LEDS for the magstrip reader to toggle in sequence to indicate a sweeping motion. Another LED for the NFC reader to blink indicating the reader is active and ready for a card. There is the touch support, the LCD display and the magstrip and NFC readers themselves (as custom interop). Last but not least is the block storage support for ExtendedWeakReferences used to save the touch screen calibration.

The engine looks like this:

using Microsoft.SPOT.Hardware;
using Microsoft.SPOT.Emulator;
using Microsoft.SPOT.Emulator.Wpf;
using Microsoft.SPOT.Emulator.Gpio;
using Microsoft.SPOT.Emulator.TouchPanel;
using Microsoft.SPOT.Emulator.BlockStorage;
 
namespace KioskEmulator
{
    public class KioskEmulatorEngine : Emulator2
    {
        static class Pins
        {
            public const Cpu.Pin Select = (Cpu.Pin)3;
            public const Cpu.Pin LED1 = (Cpu.Pin)48;
            public const Cpu.Pin LED2 = (Cpu.Pin)47;
            public const Cpu.Pin LED3 = (Cpu.Pin)45;
            public const Cpu.Pin RFIDLED = (Cpu.Pin)40;
 
            public const Cpu.Pin MagIrq = (Cpu.Pin)41;
            public const Cpu.Pin NfcIrq = (Cpu.Pin)42;
 
            public const Cpu.Pin Touch = TouchGpioPort.DefaultTouchPin;
        }
 
        public KioskEmulatorEngine( IEmulator Hal )
            : base( Hal )
        {
        }
 
        /// <summary>Registers default components and settings for this emulator</summary>
        protected override void LoadDefaultComponents( )
        {
            base.LoadDefaultComponents( );
 
            LED1 = RegisterPin( "LED1", Pins.LED1 );
            LED2 = RegisterPin( "LED2", Pins.LED2 );
            LED3 = RegisterPin( "LED3", Pins.LED3 );
            RFIDLED = RegisterPin( "RFIDLED", Pins.RFIDLED );
            Select = RegisterPin( "Select", Pins.Select, VirtualKey.Select );
            MagIrq = RegisterPin( "MagIrq", Pins.MagIrq );
            NfcIrq = RegisterPin( "NfcIrq", Pins.NfcIrq );
 
            RegisterLcd( 320, 240, 16, Pins.Touch );
 
            RegisterBlockStorage( );
 
            base.TimingServices.SystemClockFrequency = 16000000;
            base.RamManager.Size = 8 * 1024 * 1024;
            base.GpioPorts.MaxPorts = 129;
        }
 
        private void RegisterBlockStorage( )
        {
            EmulatorBlockStorageDevice bs = new EmulatorBlockStorageDevice( );
            bs.ComponentId = "EWRFlash";
            bs.PersistanceFilename = "EWR.Dat";
            bs.MaxSectorWriteTime = 500;
            bs.MaxBlockEraseTime = 2000;
 
            // 1 region with 6 blocks for EWR storage only
            bs.Regions = new Region[ 1 ];
            bs.Regions[ 0 ] = new Region( 1, 64 * 1024, new Block[ 6 ] );
            bs.Regions[ 0 ].Blocks[ 0 ] = new Block( BlockStatus.Usage_Storage_A );
            bs.Regions[ 0 ].Blocks[ 1 ] = new Block( BlockStatus.Usage_Storage_A );
            bs.Regions[ 0 ].Blocks[ 2 ] = new Block( BlockStatus.Usage_Storage_A );
            bs.Regions[ 0 ].Blocks[ 3 ] = new Block( BlockStatus.Usage_Storage_B );
            bs.Regions[ 0 ].Blocks[ 4 ] = new Block( BlockStatus.Usage_Storage_B );
            bs.Regions[ 0 ].Blocks[ 5 ] = new Block( BlockStatus.Usage_Storage_B );
 
            RegisterComponent( bs );
        }
 
        #region GPIO Pin Accessors
        public GpioPort Select  { get; protected set; }
        public GpioPort LED1    { get; protected set; }
        public GpioPort LED2    { get; protected set; }
        public GpioPort LED3    { get; protected set; }
        public GpioPort RFIDLED { get; protected set; }
        public GpioPort MagIrq  { get; protected set; }
        public GpioPort NfcIrq  { get; protected set; }
        #endregion
    }
}

 

Not a lot to it really the engine is derived from the Emulator2 base class that provides a number of helpful methods for registering GPIO pins and the LCD.The static Pins class provides constant pin values of the proper Cpu.Pin type (avoids casting in lot’s of places) These are all set to match what the actual hardware uses so the application code will work correctly. The accepts an IEmulator interface for custom emulator CLR+HAL implementations. This allows a custom emulator such as this to use a device specific emulator CLR+HAL and is typically used for adding interop extensions. This extensibility can also provide an emulator CLR implementation that exactly matches the features (APIs and classes supported) in the firmware of a real device. (E.g. a device with no actual display could have a customized CLR implementation that won’t support any of the graphics classes and methods so you get exact behavior of the real device.)

The device emulated by KioskEmulatorEngine has a set of hardware that must be configured for the emulation to function correctly. This is done through the overloaded LoadDefaultComponents() method. LoadDefaultComponents() is called by the Microsoft.SPOT.Emulator.Emulator class during initialization and allows a derived class to register EmulatorComponents in the system. This implementation registers several GPIO Pins using the extension methods provided by Emulator2. Each pin gets a name, that is the component ID for the underlying EmulatorCompontent, and the pin number. The RegisterPin function will create a new GpioPort instance, register it and return the new port. The port is then stored for later re-use. Storing the GpioPort saves looking it up again via the FindComponentByID or through the GpioPorts collection. It also allows use of the port before the emulator reaches the Initialized state as the GpioPorts collection is not filled in with all the registered ports until just before transitioning to the initialized state. If  you try to use the collection before reaching the initialized state you get an exception since it is still empty.

After registering GPIOs the LoadDefaultComponents() registers the LCD with screen dimensions of 320x240x16 and enabling Touch on the previously defined touch pin number. The LCD sizes are in actual device pixels. This is important as the WPF UI rendering system works in terms of real world sizes and not pixels. If you have a 96dpi monitor things end up as 1:1 that we’ll see more detail on with the touch support in the engineer’s main window. Once we move to the nicer designer’s window that matches the actual size of the device on the screen. We’ll see that the total number of pixels for display area is significantly larger than the actual number of pixels on the device. Scaling is applied to make it show up as it would on the real system. This has interesting implications for touch. in the engineers view it normally ends up as 1:1 per pixel (or close enough). Thus no calibration is needed, however once you shift to the designer’s nice UI things don’t match up per pixel and you must have calibration to get touch to work. This is true of the real device so makes things a bit more like the real thing and keeps you from forgetting an important step. (Don’t worry I’ve generalized the whole calibration process into a reusable assembly. Yes, you guessed it, that’s another post for another time…)

After setting up the LCD and touch components LoadDefaultComponents registers the block storage devices for Extended Weak references. For the emulator the storage data is stored in a file that, in this case, is called EWR.DAT. The storage has one region with 6 blocks of 64K each. The regions are split into two for 3 STROAGE_A and 3 STORAGE_B (used as a “ping pong” style transacted write memory) to match what the physical device has for storage.

After initializing the storage the LoadDefaultComponents() method will set up the system clock frequency, the RAM size and maximum number of GPIO ports.

The registered GpiPorts created and saved as public properties so that the additional code can refer to the ports as named properties instead of pin numbers or forcing code to look up the pins somehow. Each port property is publicly read only but writeable by the KioskEmulatorEngine instance. (These are set in LoadDefaultComponents() as previously discussed)

That’s all there is to it. Focused, to the point and all specific to the hardware being emulated without any additional clutter. In my next post we’ll look at the Emulator2 base class to see what else is going on with that class to take advantage of. So, as they used to say on The Muppet Show, “Tune in next time and hear Dr. Bob say…”

Posted by smaillet | 0 Comments

Building a WPF Emulator Part II

OK, this time we’ll get to some code. (and a new blog theme style that makes fitting code a lot easier!) In previous posts I’ve outlined the concepts involved with links to more detailed info on the general patterns etc… Now we’ll have a look at some actual code for a .NET Micro Framework device emulator.

Look Ma – no Main()

You can create a WPF based application from the Visual Studio project templates. It will create a basic application with a main window. One thing you will notice straight off, if you haven’t done any WPF programming before, is that the .CS code files are not quite where you’d expect. They are a node under the application and window .XAML files. The application.cs file is practically empty and so is the window.cs file. If you are anything like me you’ll be pulling your hair out and screaming at your computer screen “Where the #$%*! is Main()?”. Funny thing about using WPF and XAML – it’s not needed. The XAML code will be used to generate one for you! (Yeah, I know that’s a bit creepy, but you get used to it in time! ;-) )

The application

To work with the emulator you need to modify the application.cs file to start the emulation engine. This is a bit different from the standard way in which you normally do things in a Forms based emulation. Traditionally you start the UI from within the emulation object by starting a new thread for the UI. I’ve always thought that was a bit backwards as all the UI templates etc.. for Forms and WPF make the UI start and run on the applications main thread. So I decided that with a new WPF library it was worth working with the tools and templates rather than against them. Thus the UI runs on the main thread as expected and the emulation engine runs on a background thread.

using System;
using System.Windows;
using Microsoft.SPOT.Emulator;
using Microsoft.SPOT.Emulator.Wpf;
 
namespace KioskEmulator
{
    public partial class App
    {
        KioskEmulatorEngine Engine;
        KioskEmulatorViewModel ViewModel;
 
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup( e );
 
            // create a new emulator instance
            KioskEmulatorEngine eng = 
                new KioskEmulatorEngine(new EmulatorNative());
 
            // let the view model connect to the emulator events
            // *before* starting the emulator, otherwise it might
            // miss the initialize event. (E.g. try to connect
            // after the one time event is fired.)
            this.ViewModel = new KioskEmulatorViewModel(eng);
 
            this.Engine = eng;
            this.Engine.StartEmulator( );
        }
 
        protected override void OnActivated(EventArgs e)
        {
            base.OnActivated(e);
 
            // Setting the DataContext here instead of in XAML
            // is an optimization (see: 
            // http://msdn.microsoft.com/en-us/library/cc656914.aspx )
            // it also ensures that the engine the viewmodel connects
            // to is started before the databinding starts trying to
            // access it.
            // only hook up the data context the first time the
            // Application is activated
            if( this.MainWindow.DataContext == null )
                this.MainWindow.DataContext = this.ViewModel;
        }
 
        protected override void OnExit(ExitEventArgs e)
        {
            base.OnExit(e);
 
            // shut down the emulator engine if it isn't already
            // shutting down
            if(  Engine.State != Emulator.EmulatorState.ShutDown
              && Engine.State != Emulator.EmulatorState.Uninitialize
              )
            {
                Engine.Stop();
            }
        }
    }
}

The application code is pretty simple really. There is a custom class KioskEmulatorEngine that is derived from the standard Emulator class provided by Microsoft.  There is also a Custom ViewModel called KioskEmulatorViewModel that overrides the OnStarup method to create a new View Model and emulation engine. It then binds the two together and starts the emulator running. (Note: the use of new EmulatorNative() as the parameter to a custom EmulatorComponent derived class is to support custom interop in the emulator’s HAL – that’s an entirely different set of blog articles for a later date. ) OnExit handles shutting down the emulator if it isn’t already in the process of shutting down. The OnActivated() method is a bit special it handles setting the DataContext for data binding. This is done in the OnActivated() handler for two reasons. First off it is a performance optimization as recommended by MSDN documentation. Secondly it helps to ensure that the Emulator is ready to be accessed by data binding (through the ViewModel) before actually starting any binding operations. (We’ll get to data binding in more details when we look at the XAML code in a later post)

The following is a diagram of the core classes involved in the application:

image

Click the image to enlarge.

Emulatro2 is a new class derived from the standard Emulator to add events for the Initialize and Uninitialize handling. It is part of the standard WPF emulator library created for this sample.

In my next post we’ll take a look at the KioskEmulatorEngine implementation and then at the ViewModel. The application, emulator engine and the ViewModel for the heart of the emulation. With just those components you can fully automate and unit test the emulator without any need for a visible UI. That’s pretty cool. This is all due to the power of the Model+View+ViewModel pattern used in WPF.

Building a WPF Emulator – Part 1

So, you want to know more about building an emulator with WPF? Well, so did I. Of course the first question to ask when encountering something new is why bother? (E.g. What’s it going to do for me that the stuff I already have isn’t going to do?) Well in the case of WPF, it’s going to do a LOT. More than I could possibly cover in this blog series. However, there is a major theme of WPF that has a big impact on creating an emulator. Separation of the UI from the business logic of an application. This isolation of concerns is key to making an application look great without a lot of headache. The engineers can create a basic functional, but ugly and clumsy UI then hand things over to a designer who makes it all look great without modifying the code. I wanted to maintain that theme with the emulator. In particular I wanted to whip up something quick and ugly to get on with testing code, but I also wanted something that looked like the real device, which meant a non-rectangular window and GUI control to replace the normal functionality found on a Window’s tile bar. As an Example, here’s a screen shot of the “engineer’s design”:

image

Not exactly pretty, eh? But it works and let’s me get on with testing things. (Don’t worry I will make it look a LOT better in a later post and I won’t have to change a single line of the rest of the emulator code to do it either!) There are a few items on the screen worth discussing. There are some buttons acting as LEDs that will change color when the LED is on. There is a “Select” button which is acting as a GPIO button on the device. (The actual unit doesn’t have any buttons but having that was useful for running some of the test applications provided in the SDK like the touch calibration samples.) The box with the text “Click Anywhere” is the LCD display area showing the Touch sample application running on the emulator. The Nfc Reader and MagStrip areas are just simple boxes with Drag and drop support to allow dropping a file onto each region to trigger interrupts into the emulator.

The card reader items support more than just an interrupt, the data is read from the file and fed back up to the .NET Micro Framework application from within the emulator. Thus the application doesn’t need to know it’s on an emulated system. The card readers are implemented with a custom interop library with a special version for the emulator to handle moving the data from the emulation into the .NET MF application.

Implementing this UI with the XAML designer built into Visual Studio 2008 is rather easy. Drop a canvas element on to the window and then add the other items. (Enabling the LCD, select button and touch support requires the WPF emulator library this series of articles will detail.) Using a canvas like this is generally not the best idea. However it makes for a quick and dirty UI that’s easy for an engineer familiar with Windows Forms to get on with things. In my next post in this series I’ll cover the actual XAML code for this UI and the WPF emulator library features it uses. Then we’ll dig into the “Model-View-View Model” design pattern in a bit more detail and apply it to the emulator to create a view model for the custom emulator diving into the details of the library and eventually ending up with a nice pretty UI for the emulated KIOSK device.

More Posts Next page »
 
Page view tracker