Sunday, 19 May 2013

LongTouch event on single-touch LCD

I have a T35 LCD touchscreen as part of my Gadgeteer kit. I was disappointed to find that although the drivers for the screen suggested gestures, in fact the display is a single-touch and so registers only TouchDown and TouchUp events.

I needed a second gesture for an app I was writing so created a subclass of the Display_T35 class. Here's how it works.

The Class

As it subclasses the Display_T35 class, it implements the public constructors of that class. There's one additional parameter on each constructor; the interval in milliseconds after which the LongTouch event will fire - this defaults to a second. The constructors also register handlers for the TouchDown and TouchUp events of the base class.

    public class GestureEnabledDisplay_T35 : Gadgeteer.Modules.GHIElectronics.Display_T35
    {
        public GestureEnabledDisplay_T35(int socket1, int socket2, int socket3, long longTouchRegisterInterval = 1000)
            : base(socket1, socket2, socket3)
        {
            Initialise(longTouchRegisterInterval);
        }

        public GestureEnabledDisplay_T35(int socket1, int socket2, int socket3, int socket4, long longTouchRegisterInterval = 1000)
            : base(socket1, socket2, socket3, socket4)
        {
            Initialise(longTouchRegisterInterval);
        }

        private void Initialise(long longTouchRegisterInterval)
        {
            base.WPFWindow.TouchDown += new Microsoft.SPOT.Input.TouchEventHandler(WPFWindow_TouchDown);
            base.WPFWindow.TouchUp += new Microsoft.SPOT.Input.TouchEventHandler(WPFWindow_TouchUp);
            LongTouchRegisterInterval = longTouchRegisterInterval;
        }
The subclass needs to expose the new LongTouch event. This is the .Net Micro Framework, so generic event handlers are not available - remember .Net 1.1 anyone?

        public delegate void LongTouchEventHandler(object sender, EventArgs args);
        public event LongTouchEventHandler LongTouch;
        
  private void OnLongTouch()
        {
            if (LongTouch != null)
            {
                LongTouch(this, EventArgs.Empty);
            }
        }
The functionality is fairly simple. When the TouchDown event is raised, the current clock tick is recorded. When the TouchUp event is raised, the number of ticks since TouchDown is calculated and compared with the LongTouchRegisterInterval. If the interval has passed, the LongTouch event is raised.

        public long LongTouchRegisterInterval { get; private set; }

  private long _touchdownTicks;
        private const long NanosecondsInMilliseconds = 10000;

        void WPFWindow_TouchUp(object sender, Microsoft.SPOT.Input.TouchEventArgs e)
        {
            var touchupTicks = DateTime.Now.Ticks;
            if (touchupTicks - _touchdownTicks > (NanosecondsInMilliseconds * LongTouchRegisterInterval))
            {
                OnLongTouch();
            }
        }

        void WPFWindow_TouchDown(object sender, Microsoft.SPOT.Input.TouchEventArgs e)
        {
            _touchdownTicks = DateTime.Now.Ticks;
        }

The Usage

If you use the standard Gadgeteer designer to connect your module...
...you'll have an instance of the Display_T35 defined for you in the generated.cs file:

        private Gadgeteer.Modules.GHIElectronics.Display_T35 display;

        private void InitializeModules()
        {
            this.display = new GTM.GHIElectronics.Display_T35(14, 13, 12, 10);
        }
This will need to be edited to use the new GestureEnabledDisplay_T35 class

        private GestureEnabledDisplay_T35 display;

        private void InitializeModules()
        {
            this.display = new GestureEnabledDisplay_T35(14, 13, 12, 10);
        }
However, this means that each time you edit the diagram in the designer, your changes will be overwritten. And the generated class is called generated for a reason - it's not yours so keep your mitts off. A better way to create the display class is to leave the module unconnected in the designer, and create the class explicitly in your code.

    public partial class Program
    {
        GestureEnabledDisplay_T35 gestureEnabledDisplay;

        void ProgramStarted()
        {
            gestureEnabledDisplay = new GestureEnabledDisplay_T35(14, 13, 12, 10);
            gestureEnabledDisplay.LongTouch += new GestureEnabledDisplay_T35.LongTouchEventHandler(display_LongTouch);
        }
 }

Known Issues

There are a couple of annoyances with the implementation, but not enough to make me swear lots:

  • The TouchDown and TouchUp events are defined in the Display_T35.WPFWindow class, but the LongTouch event is defined in the Display_T35 class.
  • If the WPFWindow.TouchUp event is handled as well as the LongTouch event, both events will still fire - the LongTouch event does not swallow the TouchUp event.

Where's the code?

The code's available as a GitHub Gist, here.

Saturday, 18 May 2013

CLR_E_FAIL in .Net Micro Framework

While porting a library from .Net 4.5 to .Net Micro Framework 4.2, I had a large number of build failures - mainly the expected errors around generics and LINQ, which are not available in the Micro Framework.

Having worked my way through the obvious failures - IEnumerable<T> to arrays, EventHandler<T> to delegate(object, EventArgs), the compiler was reporting this:
I presumed the Micro Framework was having trouble with the foreach keyword, so changed the code to use a standard for loop. Then I received this error:


It turns out that what the Micro Framework doesn't like is multi-dimensional arrays. Where I had Points defined as Point[,] it needed to be defined as Point[][]. It was easy enough to fix, but a meaningful error message would have saved some of Google's bandwidth.

Sunday, 28 April 2013

The DevSouthCoast hacking bee photo-story

I spent a weekend with a bunch of developers and a bunch of electronics hardware. The problem we were trying to solve was to build a "beehive monitoring device". Bees are dying out and nobody knows why. There are many theories: parasites, pesticides, reduced hedgerows, overwork. What's certain is that numbers are dwindling, so the weekend was dedicated to producing a low-cost high-tech one-size-fits-all monitoring device for beehives.

The monitoring equipment was supplied by the Microsoft Gadgeteer team and consisted of a power module, a main board and a bunch of sensors (temperature, humidity, motion, light, colour, GPS), communication devices (low-frequency radio, WiFi, GSM, bluetooth), user input (buttons, touch-screen LCDs, joysticks) and output (LCD displays, coloured LEDs, SD card) and more. I can't remember all of it, there was loads.

The bee knowledge was supplied by a local beekeeper who answered all of our questions about the bees and hives with a great deal of patience, then took us to the on-site beehives for a tour. I like bees, but have discovered I don't like defensive bees so didn't hang around for long.

Back in the sweatshop, the 12 developers neatly split into 3 teams of 4, with a seasoned Gadgeteer user and 3 novices in each. The suggestion of naming the teams "drones", "workers" and "queens" was not taken up.

Each team beavered away trying to solve the problem of non-intrusive bee monitoring and came up with a host of ideas. The three demonstrated solutions had a common core of regularly logging temperature and humidity data to an SD card, but the solutions for publishing the data varied across teams. One team's solution was to use a bluetooth component to download the log file contents to a bluetooth device; one's was to send notifications via RF link to a remote device to display information on an LCD screen; the other's was to use a WiFi connection to upload the data to a website to be displayed on a web page, and to send SMS messages for alerting special conditions.

The lucky members of the winning team (including yours truly) each took home an impressive set of Gadgeteer components. Expect more Gadgeteer-related posts soon as I discover what I can do with them!

Monday, 25 March 2013

C# syntactic sugar - the event keyword

The event keyword is a great example of syntactic sugar. The following class definition
    public class Button
    {
        public event EventHandler Pushed;
    }
results in the following code being generated
    public class Button
    {
        private EventHandler _pushed;

        public event EventHandler Pushed
        {
            add
            {
                EventHandler eventHandler = this._pushed;
                EventHandler comparand;
                do
                {
                    comparand = eventHandler;
                    eventHandler = System.Threading.Interlocked.CompareExchange<EventHandler>(ref this._pushed, comparand + value, comparand);
                }
                while (eventHandler != comparand);
            }
            remove
            {
                EventHandler eventHandler = this._pushed;
                EventHandler comparand;
                do
                {
                    comparand = eventHandler;
                    eventHandler = System.Threading.Interlocked.CompareExchange<EventHandler>(ref this._pushed, comparand - value, comparand);
                }
                while (eventHandler != comparand);
            }
        }
    }
In .Net, an event is a special type of multicast delegate which can only be invoked from the class or struct where it is declared. Any number of subscriptions can be added to the event, which will be called in order when the event is raised.

The add and remove blocks that manage event subscriptions are generally auto-implemented, but they can easily be overridden. As you can see from the code above, the compiler-implemented code uses the System.Threading.Interlocked.CompareExchange method to guarantee thread safety around the adding and removing of subscriptions.

Sunday, 24 March 2013

C# syntactic sugar - the using statement

The C# using statement (as opposed to the using directive) is usually described along the lines of syntactic sugar for a try/finally block that guarantees to call the Dispose method of a class or struct that implements IDisposable. This is correct except for a subtle detail that I'll explain in a while.

Consider the following code:
using System;

public class Program
{
    public static void Main(string[] args)
    {
        using (var myDisposable = new MyDisposable())
        {
            myDisposable.DoThing();
        }
        // not allowed, myDisposable is out of scope
        //myDisposable.DoThing();
    }
}

public class MyDisposable : IDisposable
{
    public void DoThing()
    {
        // method intentionally left blank
    }

    public void Dispose()
    {
        Console.WriteLine("Disposed");
    }
}
Assuming the standard description of the using statement, this is how lines 7-12 above are expanded by the compiler:
        var myDisposable = new MyDisposable();
        try
        {
            myDisposable.DoThing();
        }
        finally
        {
            if (myDisposable != null)
            {
                ((IDisposable)myDisposable).Dispose();
            }
        }
        // not allowed, myDisposable is out of scope
        //myDisposable.DoThing();
However, the comment at line 13 is no longer correct; the variable myDisposable is now available in the whole method following its declaration.

Variable Scope

Assuming a variable is declared within the using statement, the compiler will scope that variable, by adding a set of braces around its usage. Here's the full method as it is compiled - note the braces at lines 3 and 16:
    public static void Main(string[] args)
    {
        {
            var myDisposable = new MyDisposable();
            try
            {
                myDisposable.DoThing();
            }
            finally
            {
                if (myDisposable != null)
                {
                    ((IDisposable)myDisposable).Dispose();
                }
            }
        }
        // not allowed, myDisposable is out of scope
        //myDisposable.DoThing();
    }
Of course, it is possible to live more dangerously by applying the using statement on a variable declared outside scope of the using statement:
    public static void Main(string[] args)
    {
        var myDisposable = new MyDisposable();
        using (myDisposable)
        {
            myDisposable.DoThing();
        }
        // careful, myDisposable has been disposed
        myDisposable.DoThing();
    }
... if you do that, good luck.

C# syntactic sugar - the params keyword

This is the second in what might soon be a series of blogposts on C# syntactic sugar - that is, where the language allows you to express your intent using a keyword, and the compiler restructures the code to perform how you expect it to.

The params Keyword

This post is about the params keyword. This keyword allows you to define an array parameter to a method, which can be specified by its caller as a list of values. Here's an example that demonstrates the flexible nature of the parameter:
        public static void Main(string[] args)
        {
            // All valid calls
            DoStuff();
            DoStuff(1);
            DoStuff(1, 2);
            DoStuff(new[] { 1, 2 });
        }

        private static void DoStuff(params int[] ints)
        {
            // this method intentionally left blank
        }

The IL

So, what does the compiler does with this? Here's the IL that the compiler produces for the DoStuff method, with the interesting bit highlighted:

.method private hidebysig static void DoStuff(int32[] ints) 
cil managed 
{
 .param [1]
 .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 )
 // Code size 2 (0x2)
 .maxstack 8
 IL_0000: nop
 IL_0001: ret
} // end of method Program::DoStuff

The Compiler

So, the code that the compiler is actually producing looks like this:

        private static void DoStuff([System.ParamArray] int[] ints){
            // this method intentionally left blank
        }

However if you try to compile this code, the C# compiler gives this message:


Clearly this is more than syntactic sugar, it's a requirement!

Saturday, 23 March 2013

C# syntactic sugar - the lock statement

Inspired by a talk I saw a DevWeek 2013 by Andrew Clymer, I took a look at the IL created by the C# compiler when the lock keyword is used. If you don't need an introduction to how the lock statement works, scroll down a bit and skip the first couple of C# snippets.

The Lock Statement

As a brief introduction to the lock keyword, it is used as a mechanism to allow access by a thread to a critical piece of code. Typically, this is when you have the possibility of multiple threads trampling on each other's data.

Take the sample code here:
using System;
using System.Threading;
using System.Threading.Tasks;

public class Program
{
    public static void Main(string[] args)
    {
        // Create a totaliser
        var totaliser = new Totaliser();

        // Set it off on a new thread
        Task.Run(() => totaliser.ModifyTotal());

        // Give the totaliser a chance to do something
        Thread.Sleep(100);

        // Write the current total
        Console.WriteLine(string.Format("Current value of Total: {0}", totaliser.Total));
        Console.ReadLine();
    }
}

public class Totaliser
{
    public int Total { get; private set; }

    // increment the total to 500, then down again to 0
    public void ModifyTotal()
    {
        for (var counter = 0; counter < 5000000; ++counter)
        {
            Total++;
        }
        for (var counter = 0; counter < 5000000; ++counter)
        {
            Total--;
        }
    }
}
The intent of the Totaliser class is to be able to freely increment and decrement its Total without any external visibility of what's happening. Unfortunately, because its Total property is publicly readable, the Total can be read at any stage in the increment-decrement cycle in a multi-threaded environment:

A solution to this problem is to use the lock statement, around the reads and writes to Total:
using System;
using System.Threading;
using System.Threading.Tasks;

public class Program
{
    public static void Main(string[] args)
    {
        // Create a totaliser
        var totaliser = new Totaliser();

        // Set it off on a new thread
        Task.Run(() => totaliser.ModifyTotal());

        // Give the totaliser a chance to do something
        Thread.Sleep(100);

        // Write the current total
        Console.WriteLine(string.Format("Current value of Total: {0}", totaliser.Total));
        Console.ReadLine();
    }
}

public class Totaliser
{
    private object lockObject = new object();

    private int _total;
    public int Total
    {
        get
        {
            lock (lockObject)
            {
                return _total;
            }
        }
        private set { _total = value; }
    }

    // increment the total to 500, then down again to 0
    public void ModifyTotal()
    {
        lock (lockObject)
        {
            for (var counter = 0; counter < 5000000; ++counter)
            {
                Total++;
            }
            for (var counter = 0; counter < 5000000; ++counter)
            {
                Total--;
            }
        }
    }
}
See the new lockObject at line 26, and the lock statement at lines 33 and 44.

The lock statement forces the thread to obtain a lock on the lockObject before it can proceed; if another thread has the lock, it must wait until it's been released. The result is a success:

The IL

Looking at the IL produced by the compiler, you can see the framework objects used to implement the lock:

.method public hidebysig specialname instance int32 
        get_Total() cil managed
{
  // Code size       48 (0x30)
  .maxstack  2
  .locals init ([0] bool '<>s__LockTaken0',
           [1] int32 CS$1$0000,
           [2] object CS$2$0001,
           [3] bool CS$4$0002)
  IL_0000:  nop
  IL_0001:  ldc.i4.0
  IL_0002:  stloc.0
  .try
  {
    IL_0003:  ldarg.0
    IL_0004:  ldfld      object Totaliser::lockObject
    IL_0009:  dup
    IL_000a:  stloc.2
    IL_000b:  ldloca.s   '<>s__LockTaken0'
    IL_000d:  call       void [mscorlib]System.Threading.Monitor::Enter(object, bool&)
    IL_0012:  nop
    IL_0013:  nop
    IL_0014:  ldarg.0
    IL_0015:  ldfld      int32 Totaliser::_total
    IL_001a:  stloc.1
    IL_001b:  leave.s    IL_002d
  }  // end .try
  finally
  {
    IL_001d:  ldloc.0
    IL_001e:  ldc.i4.0
    IL_001f:  ceq
    IL_0021:  stloc.3
    IL_0022:  ldloc.3
    IL_0023:  brtrue.s   IL_002c
    IL_0025:  ldloc.2
    IL_0026:  call       void [mscorlib]System.Threading.Monitor::Exit(object)
    IL_002b:  nop
    IL_002c:  endfinally
  }  // end handler
  IL_002d:  nop
  IL_002e:  ldloc.1
  IL_002f:  ret
} // end of method Totaliser::get_Total


System.Threading.Monitor

Does that mean we could use the System.Threading.Monitor class to manually implement our own lock? Yes, of course. A simple C# lock statement such as
        lock (lockObject)
        {
            DoSomething();
        }
actually gets compiled as if the C# statements were
        object obj = (System.Object)lockObject;
        System.Threading.Monitor.Enter(obj);
        try
        {
            DoSomething();
        }
        finally
        {
            System.Threading.Monitor.Exit(obj);
        }
The System.Threading.Monitor class has a couple of options when trying to grab a lock on an object, in particular the TryEnter method. This has an overload that takes a timeout value in milliseconds, which specifies how long this thread should wait to obtain the lock
        object obj = (System.Object)lockObject;
        if (System.Threading.Monitor.TryEnter(obj, 3))
        {
            try
            {
                //Do something
            }
            finally
            {
                System.Threading.Monitor.Exit(obj);
            }
        }
        else
        {
            //Do something else
        }
I don't advocate rewriting your lock statements to use the longhand versions above, but this hopefully removes a layer of abstraction between you and your multi-threaded executable.