20 September 2015

Controlling a fan using a UWP on a Raspberry PI2 remotely

Part 4 of Reading temperatures & controlling a fan with a RP2, Azure Service Bus and a Microsoft Band

Intro
This article shows you how to control a device attached to a Raspberry PI2 remotely - that is, the Universal Windows App on the PI2 listens to commands coming off an Azure Service Bus queue.I have explained several details already in the previous posts in this series - I will go over some things more quickly than before.

The fan is controlled using a Keyes SRD-05VDC-SL-C switch, as displayed here to the right. This is a relay that controls mains power. The Raspberry PI2 is a very low power device operating in the 5V range, so controlling mains power (100-250V depending where you live) requires there be something in between the Raspberry and the actual mains power - this little device here. Connecting the mains power directly to the poor PI2's GPIO pins would most likely result in a spectacular but rather short fireworks, so that's quite inadvisable to do.

Basic app setup
As I explained before, I have set up this app using dependency injection, basically creating a set of very loosely couples objects that interact only through interfaces and/or events - an getting objects of which they are dependent on supplied via their constructor, in stead of newing them up themselves.

So, once again we have a look an the MainPage_Loaded in MainPage.xaml.cs of the TemperatureReader IoT app, and I have grayed out everything that is does not play a role in controlling the fan.

var gpioService = new GpioService();
var fanSwitch = new SwitchDevice(gpioService, Settings.SwitchPinId);
var controller = new AnalogTemperatureSensorController(gpioService);
var thermometer = new Thermometer(gpioService, controller);
var poster = new TemperatureQueueClient(QueueMode.Send);
var fanCommandListener = new FanSwitchQueueClient(QueueMode.Listen);
await fanCommandListener.Start();

fanCommandListener.OnDataReceived += (cs, cmd) =>
{
  Debug.WriteLine(
    $"Fanswitchcommand received {cmd.Status}; current status fan on = 
      {fanSwitch.IsOn} at {DateTime.Now}");
  fanSwitch.SwitchOn(cmd.Status == FanStatus.On);
};

The amusing thing about this, as attentive readers will see, is that I am using no new objects whatsoever. All the object types in this are already described in previous posts of this series.

So how does this work?
As soon as the app is loaded, the GpioService, which I already explained in my previous post - is created. Then the fanSwitch object is created. This is a SwitchDevice - also already explained in the previous post as a base class for a class that controls an LED, and that now controls a SRD-05VDC-SL-C - by virtue of using a different GPOI pin. Then there is a FanSwitchQueueClient created - that listens to commands coming from the Azure Service bus. The working of this class is explained in the second post of this series.

Then finally, an event handler is attached to the FanSwitchQueueClient OnDataReceived - a very little piece of code that sets the switch to the status as requested by the command coming from the Azure Service Bus.

There is also this little piece of code reports back not only the temperature but also the current fan status back to whoever is listening to the other service bus

thermometer.OnTemperatureMeasured += async (thObject, data) =>
{
  data.FanStatus = fanSwitch.IsOn ? FanStatus.On : FanStatus.Off;
  await poster.PostData(data);
};

And that, my friends, is basically all. Nothing new - just reuse what is already been built. So why 'waste' a whole blog post on it? Mostly to show that with the right architecture you can make very easily reusable and connectable components - kind of like IoT hardware.

One more thing
There is an oddity to the SRD-05VDC-SL-C in relation to Windows 10 on Raspberry PI2: as soon as you open the pin to which it is connected and set its drive mode  to output, the SRD-05VDC-SL-C switches itself on. A very undesirable state of affairs. This is why the constructor of SwitchDevice contains a statement to switch it off immediately:

public SwitchDevice(IGpioService gpioCtrl, int pinId)
{
  _pinId = pinId;
  _gpioCtrl = gpioCtrl;
  SwitchOn(false);
}

Sometimes you can briefly see the red status LED of the SRD-05VDC-SL-C blink red when it is initialized like this. Be aware that there may be a short power spike in the attached mains power, and be sure the device that run on mains power can handle it.

Check the demo solution here.

17 September 2015

Measuring temperatures using an UWP on a Raspberry PI 2

 

Part 3 of Reading temperatures & controlling a fan with a RP2, Azure Service Bus and a Microsoft Band

Intro
In this article I will show how you can measure temperature on a Raspberry PI2 using an Universal Windows Platform App. To this extent we will use a Keyes Analog-temperature sensor and an ADC0832 analog-digital-convertor, as well as a 2-color (red-yellow) LED to show what's happening (and whether anything is happening at all) when running headless



The hardware configuration has already been detailed in the first post of this series, this post will only detail a part of software.

Basic app setup
I have built this app using dependency injection, although not a very fancy sort, inspired by a colleague and some things I saw recently in code. The app that is intended to run on the Raspberry PI2  is called TemperatureReader (I have never been good at original names) and (mostly) TemperatureReader.Logic. You can find all the code in the demo solution. But of course I will highlight the way it's done.

All the UI that ss in the app it this single big TextBlock showing the temperature:

<Grid >
  <TextBlock Name="TemperatureText" 
             VerticalAlignment="Center" 
             HorizontalAlignment="Center" FontSize="100"></TextBlock>
</Grid

for I assume this device to run headless, but if it does not, it is nice to see something, right. In earlier post I already alluded to setting up this app as the default apps on a Raspberry PI2, which implies that whatever it does, it should start automatically. And although the UI does not amount to much, I have used the MainPage.xaml.cs to create all objects that are necessary and 'connect the dots' between them. You will see there's actually very little functionality there. In the MainPage_Loaded I first create all 'actors' in this dance of IoT controlling objects:

var gpioService = new GpioService();
var fanSwitch = new SwitchDevice(gpioService, Settings.SwitchPinId);
var controller = new AnalogTemperatureSensorController(gpioService);
var thermometer = new Thermometer(gpioService, controller);
var poster = new TemperatureQueueClient(QueueMode.Send);
var fanCommandListener = new FanSwitchQueueClient(QueueMode.Listen);

I have grayed out two lines, as they will be part of the next blog post. Then, a little bit lower, you see how these objects interact:

thermometer.OnTemperatureMeasured += async (thObject, data) =>
{
  data.FanStatus = fanSwitch.IsOn ? FanStatus.On : FanStatus.Off;
  await poster.PostData(data);
};

await poster.Start();
await thermometer.Start();

I use a bit of primitive dependency injection here, and keep the separate tasks - well, separated - and use only events and/or interfaces to loosely couple these objects. You will see all major objects have interfaces defined on them, and are only accessed using those interfaces - for instance, the constructor of the AnalogTemperatureSensorController expects an IGpioService, not a GpioService.

Anyway,  I first create a base object GpioService, that will allow for some low level access to the Gpio pin. Then I create a low-level controller for the analog temperature controller, which is also pretty low level - and actually more controls the A/D converter than the temperature sensor itself. This uses the Gpio service (via it's interface) so it does not have to new up all that stuff itself. The Thermometer class is the class that actually exposes the temperature to the outside world, and also gives an indication of things happening using the LED. Finally, the TemperatureQueueClient, connected to the Thermometer by an OnTemperatureMeasured event subscription, simply posts temperature data on the Azure Service Bus queue as explained in the previous blog post

You will also notice there's another method in MainPage.xaml.cs is connected to the Thermometer.OnTemperatureMeasured but that is only used to display the temperature on the screen, and make the text in red and show some debug data when new data is received (so you can even see it's still posting data when the temperature has not changed):

private async void OnTemperatureMeasured(object sender, TemperatureData e)
{
  Debug.WriteLine(
   $"MainPage.OnTemperatureMeasured {e.Temperature}: {e.IsValid} at {DateTime.Now}");
  if (e.IsValid)
  {
    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
    {
      var brush = TemperatureText.Foreground;
      TemperatureText.Text = $"{e.Temperature}°C";
      TemperatureText.Foreground = new SolidColorBrush(Colors.Red);
      await Task.Delay(250);
      TemperatureText.Foreground = brush;
    });
  }
}

The Gpio Service
This is actually a very simple class, and it's intent is to remove the necessity of calling Windows.Foundation.Metadata.ApiInformation‏.IsTypePresent every time you need a GpioController. You can now simply check whether the Controller property isn't null, which is a bit easier and shorter.

using Windows.Devices.Gpio;

namespace TemperatureReader.Logic.Devices
{
  public class GpioService : IGpioService
  {
    public GpioService()
    {
      if (Windows.Foundation.Metadata.ApiInformation‏.IsTypePresent(
        "Windows.Devices.Gpio.GpioController"))
      {
        if (Controller == null)
        {
          Controller = GpioController.GetDefault();
        }
      }
    }
    public GpioController Controller { get; private set; }
  }
}

The Controller property unfortunately is defined as it's implementing class type in stead of an interface - there is, in fact an IGpioController class but that's internal. I have no idea why.

The AnalogTemperatureSensorController
This is the heart of the beast, the crux of the matter, or however you want to call this. A Raspberry PI2 cannot do much with an analog temperature sensor, as it is essentially a digital device. So as I explained before in the first blog post, we need to place an Analog/Digital converter in between and talk to that. And this converter is what this class talks to. It tries to read a temperature every five seconds and does this by

  • Initializing a read session
  • Initializing the the A/D converter
  • Read two sequences of data from the converter
  • If the result of those sequences are equal, a successful temperature reading was made
    • The value is converted into degrees Celsius (sorry folks in the USA)
    • The temperature is sent to all subscribers of the OnTemperatureMeasured event.
First things first. The constructor looks like this:
public AnalogTemperatureSensorController(
  IGpioService gpioCtrl, 
  int adcCsPinId = Settings.AdcCsPinId, 
  int adcClkPinId = Settings.AdcClkPinId, 
  int adcDigitalIoPinId = Settings.AdcDigitalIoPinId, 
  int delayMilliSeconds = Settings.DefaultTemperaturePostingDelay, 
  int maxRetries = Settings.MaxReadRetry)
{
  _gpioCtrl = gpioCtrl;
  _adcCsPinId = adcCsPinId;
  _adcClkPinId = adcClkPinId;
  _adcDigitalIoPinId = adcDigitalIoPinId;
  _delayMilliSeconds = delayMilliSeconds;
  _maxRetries = maxRetries;
  IsMeasuring = false;
}

And all you have to provide is the Gpio service. The rest has default values that come out of the Settings definitions. You will see three pins connected to the A/D converter (5, 6 and 13, see the first blog post), the time between temperature reading (5000, or 5 seconds) and the maximum number of retries the component should try before admitting failure and telling that the outside world.

The "start" method kicks the whole process off

public bool Start()
{
  if (_gpioCtrl?.Controller != null)
  {
    IsMeasuring = true;

    if (_adcDigitalIoPin == null)
    {
      _adcCsPin = _gpioCtrl.Controller.OpenPin(_adcCsPinId);
      _adcClkPin = _gpioCtrl.Controller.OpenPin(_adcClkPinId);
      _adcDigitalIoPin = _gpioCtrl.Controller.OpenPin(_adcDigitalIoPinId);
    }

    if (_task == null)
    {
      _cancellationTokenSource = new CancellationTokenSource();
      InitReadSession();
      _task = new Task(async () => 
        await ExecuteMeasuring(_cancellationTokenSource.Token));
      _task.Start();
    }
  }
  return IsMeasuring;
}

It basically initializes the pins the component needs, then creates a task that runs indefinitely and measures the temperature every 5 seconds:

private async Task ExecuteMeasuring(CancellationToken cancellationToken)
{
  while (!cancellationToken.IsCancellationRequested)
  {
    var timePassed = DateTimeOffset.UtcNow - _lastExecutionTime;
    if (timePassed > TimeSpan.FromMilliseconds(_delayMilliSeconds))
    {
      var retries = 0;
      var readStatus = false;

      while (!readStatus && retries++ < _maxRetries)
      {
        readStatus = ReadData();
        _lastExecutionTime = DateTimeOffset.UtcNow;
      }

      if (retries >= _maxRetries)
      {
        OnTemperatureMeasured?.Invoke(this, new TemperatureData {IsValid = false});
      }
      _lastExecutionTime = DateTimeOffset.UtcNow;
    }
    else
    {
      var waitTime = _delayMilliSeconds - timePassed.TotalMilliseconds;

      if (waitTime > 0)
      {
        await Task.Delay(Convert.ToInt32(waitTime), cancellationToken);
      }
    }
  }
}

It looks rather complicated, but all it does is run indefinitely (until cancelled). It reads data (temperature) every five seconds. If reading fails, it tries again for 10 times (_maxRetries, supplied by constructor) and if it still fails, it will notify the outside world. In any case, it will wait for the rest of the _waitTime (5 seconds) before a new cycle of trying to read temperature again.

The ReadData method then is implemented as follows:

private bool ReadData()
{
  int sequence1 = 0, sequence2 = 0;
  _adcCsPin.Write(GpioPinValue.Low);

  InitReadSession();
  var waiter = new SynchronousWaiter();
  InitAdConverter(waiter);

  //Read the first sequence
  for (var i = 0; i < 8; i++)
  {
    _adcClkPin.Write(GpioPinValue.High);
    waiter.Wait(2);
    _adcClkPin.Write(GpioPinValue.Low);
    waiter.Wait(2);
    sequence1 = sequence1 << 1 | (int)_adcDigitalIoPin.Read();
  }

  //Read the second sequence
  for (var i = 0; i < 8; i++)
  {
    sequence2 = sequence2 | (int)_adcDigitalIoPin.Read() << i;

    _adcClkPin.Write(GpioPinValue.High);
    waiter.Wait(2);
    _adcClkPin.Write(GpioPinValue.Low);
    waiter.Wait(2);
  }

  _adcCsPin.Write(GpioPinValue.High);

  if (sequence1 == sequence2)
  {
    OnTemperatureMeasured?.Invoke(this,
      new TemperatureData { IsValid = true, Temperature = 
        Math.Round(((255 - sequence1) - 121) * 0.21875,1) + 21.8, 
        Timestamp = DateTimeOffset.UtcNow});
    return true;
  }

  return false;
}

It is important to understand that the A/D converter spits out data digital - but can do so only one bit at a time. So the whole stuff is done serially, that is: first one bit, than the other, via the _adcDigitalIoPin. But what you see are two loops. The _adcClkPin is turned on, then we wait for two milliseconds, then we turn it off again, then we wait for two milliseconds again, and then we read the _adcDigitalIoPin pin's value. We do that for every of the 8 bits. As a kind of parity, the second byte is read in the same way, but shifted in a different way into the resulting sequence variable. When the resulting integer values (sequence1 and sequence2) are the same, we have successfully read a temperature. I am not a bit shifting hero myself, so don't ask me the details, but this works. Now we only need to convert that to degrees Celsius.

From the Sunfounders manual I took a bit of code to do that, and got totally bizarre results. So I took a digital thermometer, made measurements on different times of the day and on different temperatures, and found out that the formula at the bottom of the ReadData method quite adequately converts the value the A/D converter spits out into temperatures (albeit it's mostly like 0.5-1 °C too high, but that's details. If you rebuild this with your own sensor, you might have to get some measurements yourself first to correct conversion values.

There are two important methods left: the InitReadSession method, that sets the drive mode for the three pins of the A/D converter to output

private void InitReadSession()
{
  _adcClkPin.SetDriveMode(GpioPinDriveMode.Output);
  _adcCsPin.SetDriveMode(GpioPinDriveMode.Output);
  _adcDigitalIoPin.SetDriveMode(GpioPinDriveMode.Output);
}

no rocket science there, just standard Windows 10 CoreIoT stuff - and then this gem, that is basically translated from C code in the Sunfounders manual

private void InitAdConverter(SynchronousWaiter waiter)
{
  _adcCsPin.Write(GpioPinValue.Low);
  _adcClkPin.Write(GpioPinValue.Low);
  _adcDigitalIoPin.Write(GpioPinValue.High); waiter.Wait(2);
  _adcClkPin.Write(GpioPinValue.High); waiter.Wait(2);

  _adcClkPin.Write(GpioPinValue.Low);
  _adcDigitalIoPin.Write(GpioPinValue.High); waiter.Wait(2);
  _adcClkPin.Write(GpioPinValue.High); waiter.Wait(2);

  _adcClkPin.Write(GpioPinValue.Low);
  _adcDigitalIoPin.Write(GpioPinValue.Low); waiter.Wait(2);
  _adcClkPin.Write(GpioPinValue.High);
  _adcDigitalIoPin.Write(GpioPinValue.High); waiter.Wait(2);
  _adcClkPin.Write(GpioPinValue.Low);
  _adcDigitalIoPin.Write(GpioPinValue.High); waiter.Wait(2);

  _adcDigitalIoPin.SetDriveMode(GpioPinDriveMode.Input);
}

Presumably, this in some way programs the A/D converter. The three pins get turned on and off and then there is a wait period of 2 milliseconds. What kind of instructions it gets - I have really no idea. I am guessing the 2 milliseconds have the same function as a semicolon in C# - end of statement. I hope that someone who reads this blog can enlighten me. But if you initialize the A/D converter this way, it will read temperature data in a intelligible way - that is, one that is compatible with what ReadData needs.

SynchronousWaiter
During the previous paragraph you may have noticed there are several calls to a SynchronousWaiter class. This is because I struggled with timings using await Task.Delay, but waiting for 2 milliseconds using that isn't really 2 milliseconds - it's usually more because of the callback overhead that's hidden under the hood of the await keyword. So here's SynchronousWaiter, a class the really only waits for the allotted number of milliseconds

using System.Diagnostics;

namespace TemperatureReader.Logic.Utilities
{
  class SynchronousWaiter
  {
    readonly Stopwatch _stopwatch;
    public SynchronousWaiter()
    {
      _stopwatch = Stopwatch.StartNew();
    }

    public void Wait(double milliseconds)
    {
      var initialTick = _stopwatch.ElapsedTicks;
      var desiredTicks = milliseconds / 1000.0 * Stopwatch.Frequency;
      var finalTick = initialTick + desiredTicks;
      while (_stopwatch.ElapsedTicks < finalTick)
      {

      }
    }
  }
}

and I won't pretend I wrote this myself - I was stuck on Task.Delay problems (albeit for a different sensor) and then a Microsoftie came to help

Thermometer
This class is best described as a wrapper hiding the intricacies of the AnalogTemperatureSensorController - and it handles the 'display' too, that is - it shows when data is read by blinking a LED either green or red, depending whether the temperature was successfully read or not. In addition, it shows a red/green blinking sequence when it starts up. The constructor follows the pattern we have already seen - most of what it needs (GpioService,and AnalogTemperatureSensorController) is injected to it from outside, and the pinsettings and other settings are optional and imported from the Settings class.

  public Thermometer(IGpioService gpioService, 
    IAnalogTemperatureSensorController temperatureSensorController, 
    int errorPinId = Settings.ErrorPinId, int dataPinId = Settings.DataPinId, 
    int longFlashTime = Settings.LongFlashTime, 
    int shortFlashTime = Settings.ShortFlashTime)
  {
    _gpioService = gpioService;
    _errorPinId = errorPinId;
    _dataPinId = dataPinId;
    _longFlashTime = longFlashTime;
    _shortFlashTime = shortFlashTime;
    _temperatureSensorController = temperatureSensorController;
  }

The start method initializes two pins for the LED, calls the ShowStartup method, then waits a few seconds, connects an event to the AnalogTemperatureSensorController and starts said controller (it assumes it is not started yet)

public async Task Start()
{
  _errorLed = new StatusLed(_gpioService, _errorPinId);
  _dataPinLed = new StatusLed(_gpioService, _dataPinId);

  await ShowStartup();
  await Task.Delay(WaitTimeBeforeStartup);

  _temperatureSensorController.OnTemperatureMeasured +=
     HandleTemperatureMeasured;
  _temperatureSensorController.Start();
}

The HandleTemperatureMeasure of the Thermometer class is basically just passing along the event to the outside - and blinks the LED according to the data provided by the AnalogTemperatureSensorController

async void HandleTemperatureMeasured(object sender, TemperatureData e)
{
  if (e.IsValid)
  {
    await _dataPinLed.Flash(_longFlashTime);
    OnTemperatureMeasured?.Invoke(this, e);
  }
  else
  {
    await _errorLed.Flash(_longFlashTime);
  }
}

The ShowStartup method, finally, shows the startup sequence.

private async Task ShowStartup()
{
  for (var c = 0; c < 3; c++)
  {
    _errorLed.SwitchOn(true);
    await Task.Delay(_shortFlashTime);
    _dataPinLed.SwitchOn(true);
    _errorLed.SwitchOn(false);
    await Task.Delay(_shortFlashTime);
    _dataPinLed.SwitchOn(false);
    await Task.Delay(_shortFlashTime);
  }
}
That is, it blinks the LED red-green for a couple of times. Note this is a yellow-red light, so turning the R pin only makes it red, turning on both both pins makes it green.

SwitchDevice
This is a class that is a logical wrapper for a 1-pin device that can be either turned on or off. It sports a constructor that turns the device off by default, a Switch method that sets the device to the desired state, a Toggle method that switches state, and an IsOn property that will allow you to check whether it's on or not:

using Windows.Devices.Gpio;

namespace TemperatureReader.Logic.Devices
{
  public class SwitchDevice
  {
    private readonly int _pinId;
    private readonly IGpioService _gpioCtrl;
    private GpioPin _pin;

    public SwitchDevice(IGpioService gpioCtrl, int pinId)
    {
      _pinId = pinId;
      _gpioCtrl = gpioCtrl;
      SwitchOn(false);
    }

    public void SwitchOn(bool @on)
    {
      GpioPin pin;
      if ((pin = GetPin()) != null)
      {
        pin.Write(@on? GpioPinValue.High : GpioPinValue.Low);
      }
    }

    public void Toggle()
    {
      SwitchOn(!IsOn);
    }
    
    public bool IsOn
    {
      get
      {
        GpioPin pin;
        if ((pin = GetPin()) != null)
        {
          var currentPinValue = pin.Read();
          return currentPinValue == GpioPinValue.High;
        }
        return false;
      }
    }
    
    protected GpioPin GetPin()
    {
      if (_pin == null)
      {
        if (_gpioCtrl?.Controller != null)
        {
          _pin = _gpioCtrl.Controller.OpenPin(_pinId);
          _pin.SetDriveMode(GpioPinDriveMode.Output);
        }
      }
      return _pin;
    }
  }
}

The private method GetPin makes sure the pin is initialized and sets it to the right (output) mode. But as you can see, I don't use a SwitchDevice, but a StatusLed.

StatusLed
A very simple child class of SwitchDevice that has an extra method Flash that turns on a LED for a certain number of milliseconds, then turns it off again. Easy as cake.

using System.Threading.Tasks;

namespace TemperatureReader.Logic.Devices
{
  public class StatusLed : SwitchDevice
  {
    public StatusLed(IGpioService gpioCtrl, int pinId) : 
       base(gpioCtrl,pinId)
    {
    }

    public async Task Flash(int milliseconds)
    {
      SwitchOn(true);
      await Task.Delay(milliseconds);
      SwitchOn(false);
    }
  }
}

Conclusion
As you can see, by using loosely coupled high level components you can hide a lot of the low level complexity that is going on under the hood and let those components play together in a way that makes you can still understand after returning to your code after a while. Having said that, the low level things themselves can be quite daunting and I must admit that for some things I just clung to examples in C that worked - and then translated then to C#. It does not really matter - I quite often use software libraries a well whose inner workings I don't quite understand, but I feel a bit like threading on thin ice.

Yet, I still find it awesome I can just deploy this app to a Rasbperry PI2 that is connected via WiFi, remote, directly from Visual Studio, and debug it while it runs on the device. Be aware, though, that doing so while running time-critical code like in the AnalogTemperatureSensorController will introduce all kinds spectacular error. TL;DR - don't put breakpoints in that kind of code ;)

Thanks to Jesse Caplan for his explanation of issues with Task.Delay in time-critical code and the SynchronousWaiter sample.

Check the demo solution for all code running together.

Edit 18-09-2015 - simplified SwitchDevice.Toggle method considerably after comment from @robvanu - thanks!

16 September 2015

Using system accent color brush from code in Windows 10 UWP

A very short one this time. I wanted to give some UI element the same color as the accent color, but I wanted to use it from code, not from XAML, as written for instance here.

Turns out it's called "SystemControlHighlightAccentBrush" and you can use it like this:

Brush _blinkBrush = 
  Application.Current.Resources["SystemControlHighlightAccentBrush"] 
    as SolidColorBrush;

And of course, once you know it's called "SystemControlHighlightAccentBrush" you can find it everywhere, like on Stack Overflow. So I am writing this down as much as a personal reminder as for you ;)

I used in my latest IoT demo solution that you can find here. It's in project TemperatureReader.ClientApp, class Behaviors.BlinkBehavior.

13 September 2015

Using an Azure Service bus queue for two-way (IoT) communication

 

Part 2 of Reading temperatures & controlling a fan with a RP2, Azure Service Bus and a Microsoft Band

Intro
In this post I will explain how the Windows 10 device to which the Band is paired and the Raspberry PI2 'talk' to each other. As the previous post (and the title of this post) already shows, this is done using an Azure Service Bus queue. The code for this is in two of the five projects in the demo solution

  • TemperatureReader.Shared contains the data objects shuttled over the Azure Service Bus queue, as well as all the global definitions
  • TemperatureReader.ServiceBus contains the actual code for the Service Bus code.

Getting started
Before you can get the code working, you will need to define an Azure Service Bus, because you cannot use mine - I like to keep it for demos myself and keep my Azure bill reasonable, thank you :). If you look into the TemperatureReader.Shared project in the demo solution you will find a class "Settings" that, amongst other things, has the following pretty long and rather cryptic definition:

public static readonly string TemperatureBusConnectionString =
"Endpoint=sb://yournamespacehere.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=XXXXXXXXXXXXXXXXXYOURKEYHEREXXXXXXXXXXXXXXXX";

To be able to use queues in a Service Bus, you must first claim a namespace. Doing so currently is only supported by the 'old' Azure Portal, so you need to go there to create it:
image

image[33]You need to select the tab "Service Bus" below, then hit the "Create" button. Then you get the pop-up as displayed on the right. Make up a nice namespace name (Azure will tell you if it's available or not), then select a region. As I am living in the Netherlands, I typically choose "West Europe" but feel free to choose otherwise. The rest of the settings can be left as they are - although you might consider setting the message tier to 'basic'. Hit the check mark, and you get the image below.

 

 

image

 

 

Your Azure Service bus namespace has been been created. This is stage 1 - now the actual queues need to be created. From the code in Settings.cs you can see there will need to be two queues on this Service Bus:

public static readonly string TemperatureQueue = "temperaturedatabus";
public static readonly int TemperatureQueueTtl = 10;

public static readonly string FanSwitchQueue = "fanswitchcommandbus";
public static readonly int FanSwitchQueueTtl = 10;

The first one is for sending temperature data from the PI2 to the Windows 10 device (and ultimately the Band) and the second one to send commands to switch the fan on and off. I have set the time to live (TTL) for messages on each queue at 10 seconds, meaning that any data older than 10 seconds can be discarded if it's not picked up. You can go ahead and click the arrow that I emphasized using a red box next to "thisisademo" and imageconfigure the queue manually, or just let the code (see below) to take care of it. There is only one more thing you will need to do: select the Azure Service Bus namespace that you just have created, then hit "Connection Information" at the bottom. By hovering over the text that starts with "Endpoint=sb://" you get a blue "copy" icon at the right and if you click that, that whole connection string gets put into the clipboard for your convenience.Then you can paste that into the TemperatureBusConnectionString constant in Settings.cs
image

A base queue client
In any project that you want to use Azure Service Bus in, you will need to use the NuGet package "WindowsAzure.Messaging.Managed" (assuming your are using a managed language like C# or VB.NET).
image
Then it's important to know that any client (and with that I mean an object of type Microsoft.WindowsAzure.Messaging.Queue) can both put objects in the queue as well as read them - and doing so is pretty stupid as I found out the hard way. A Queue object that does both basically eats his own messages - most of the time, but not all of the time. Happy debugging. Anyway, I wanted a queue client that

  • I could either ask to read from the queue or put data on the queue, but not both
  • could only send or receive data of a specified type
  • would automatically create a queue on the service bus if it does not exists

I came up with this:

using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Messaging;

namespace TemperatureReader.ServiceBus
{
  public class QueueClient<T> : IQueueClient<T>
  {
    private readonly string _queueName;
    private readonly string _connectionString;
    private readonly int _messageTimeToLive;
    private readonly QueueMode _queueMode;
    private Queue _queue;
    
    public QueueClient(string queueName, string connectionString, 
      QueueMode mode = QueueMode.Send, int messageTimeToLive = 10)
    {
      _queueName = queueName;
      _connectionString = connectionString;
      _queueMode = mode;
      _messageTimeToLive = messageTimeToLive;
    }

    public async virtual Task Start()
    {
      try
      {
        var settings = new QueueSettings 
          { DefaultMessageTimeToLive = TimeSpan.FromSeconds(_messageTimeToLive) };
        await Queue.CreateAsync(_queueName, _connectionString, settings);
        Debug.WriteLine($"Queue {_queueName} created");
      }
      catch (Exception)
      {
        Debug.WriteLine($"Queue {_queueName} already exists");
      }

      _queue = new Queue(_queueName, _connectionString);
      if (_queueMode == QueueMode.Listen)
      {
        _queue.OnMessage(message =>
        {
          var data = message.GetBody<T>();
          OnDataReceived?.Invoke(this, data);
        });
      }
    }

    public virtual async Task PostData(T tData)
    {
      if (this._queueMode == QueueMode.Send)
      {
        await _queue.SendAsync(tData);
      }
      else
      {
        throw new ArgumentException(
          "Cannot send data using a QueueMode.Listen client");
      }
    }

    public void Stop()
    {
      if (_queue != null)
      {
        _queue.Dispose();
        _queue = null;
      }
    }

    public event EventHandler<T> OnDataReceived;
  }
}

If a QueueClient object is created, it accepts the name of the queue, the queue connection string (that impossible long string in Settings.TemperatureBpusConnectionString), a message time-to-live and a QueueMode (can be either Send or Listen). Notice it has a type parameter - that is the type of object you are allowed to put on the queue - or can expect to come off it.

To get the thing going, you will need to call Start. This first tries to create the queue. Unfortunately I have not been able to find out how to check if a queue exists first, so I have resorted to the rather crude method of swallowing an exception if creating the queue fails - and assume that the exception was caused by an already existing queue. Then it will create an actual Queue object (Microsoft.WindowsAzure.Messaging) - and if it's a Listen QueueClient, it will attach an anonymous method to the OnMessage method of that queue. That method will hoist the data object from the queue and pass it on to whoever is subscribed to the OnDataReceived event of the QueueClient itself.

The QueueClient's post method is basically a typed wrapper on the Queue PostData method, except that it will prohibit from posting if this is a Listen client - to prevent it swallowing it's own message.

Finally there is the Stop method, that just disposes the queue.

Using specific implementations
Both TemperatureQueueClient and FanSwitchQueueClient are child classes, providing specific implementations of a queue client. For instance, TemperatureClient just handles temperature data and all you have to do is provide an override constructor to prevent you from having to set all that properties every time you use them:

using TemperatureReader.Shared;

namespace TemperatureReader.ServiceBus
{
  public class TemperatureQueueClient : QueueClient<TemperatureData>
  {
    public TemperatureQueueClient(QueueMode mode = QueueMode.Listen) :
      base(Settings.TemperatureQueue, 
        Settings.TemperatureBusConnectionString, mode, 
        Settings.TemperatureQueueTtl)
    {
    }
  }
}

The only thing there is left to set is the QueueMode, since you typically want to create one listening and one sending queue client.

If you now look in the MainPage_Loaded in MainPage.Xaml.cs in TemperatureReader (the IoT project) you will see a TempeatureQueueClient, processing temperature data, being set up as Send queue client while a FanSwitchQueueClient is a Listen queue client - which makes sense, as the Raspberry PI2 sends temperature data, but listens for commands to switch on or off the fan (ultimately coming from a Microsoft Band, somewhere in the world).

private async void MainPage_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
// stuff omitted var poster = new TemperatureQueueClient(QueueMode.Send); var fanCommandListener = new FanSwitchQueueClient(QueueMode.Listen);

In the client app that is intended for a Windows 10 device to which the Band is paired (typically a phone) it's the other way around. In MainViewModel.CreateNew you will see

public static MainViewModel CreateNew()
{
  var fanStatusPoster = new FanSwitchQueueClient(QueueMode.Send);

Indicating the queue client FanSwitchQueueClient is sending here, while the TempeatureQueueClient - embedded in TemperatureListener - is created in the constructor as a Listen client:

public TemperatureListener() 
{ 
  _client = new TemperatureQueueClient(QueueMode.Listen); 
  _client.OnDataReceived += ProcessTemperatureData; 
}

Conclusion
An Azure Service Bus client is a great way for simple one-to-one real time connections that can allow for some lag to happen between connected devices. It's very simple to use, can partly be created from code, is secured by default and does no require you to deploy a separate website to Azure to host a connection hub - the queue is hosted on Azure itself. And the awesome thing is - the code runs on both a Phone and a Raspberry PI2. It's in the same assembly. That is the power of the Universal Windows Platform.

Next time I will show how to actually measure temperature on a Raspberry PI2.

11 September 2015

Reading temperatures & controlling a fan with a RP2, Azure Service Bus and a Microsoft Band (1)

Part 1 - Idea, architecture, hardware shopping list and hardware configuration

Sometimes simple ideas have a tendency to balloon almost out of control, and this is one of them. In essence I wanted 'the other way around' compared with my previous IoT project - in stead of using the Band as a sensor device and the Raspberry PI2 as a 'display unit', I wanted to use the Band as controller. The idea was I could

  • Measure temperature using my Raspberry PI2 running Windows 10 CoreIoT
  • See the current temperature on my Band, including the date and time it was measured
  • Send a command to my Raspberry PI2 to switch on a fan if I find things are getting too hot
  • See on my Band the fan has actually switched on
  • Switch the fan off again if I feel like doing so.

Some pictures of the resulting contraption on my desk:

IMG_2040

IMG_2034

IMG_2032

I will say you this my friends: playing around with IoT stuff takes the phrase "spaghetti code" to a whole new level :D

The details
On my phone (or more precisely, the Windows 10 device to which my Band is paired) there is an app than can

  • listen to temperature data coming from the Raspberry PI2,
  • build a tile with a custom UI on my Band,
  • listen to and act on events coming from that Band UI.

If I open the custom tile on my Band, the app on my phone gets a signal to transmit the last received data from my Raspberry PI2 (the temperature, last received update date and time, and whether the fan is on or off) to the Band, followed by a single vibrate. If I tap the fan toggle button on the custom UI on my Band, the app should respond to that as well, send back a signal over the Azure Service bus queue - and display on the Band the fan is on (and can now be switched off).

On the Raspberry PI2 is a CoreIoT app that measures temperature and sends data over the Azure Service bus queue every five seconds, and also listens for fan switch on/off commands. It should also display it's 'health' by letting the connected two-color LED flash in green when a correct temperature is measured and transmitted, or red when something goes wrong. I also included a sequence on which the led rapidly blinks red/green to indicated the app is starting up. This is very handy when you set the app to be the default app - that way it's automatically started after the PI2 has booted Windows 10 CoreIoT and you can then see the app is actually starting up, even if there's no display connected.

The net result you can see on this video below:

Thanks to the Azure Service Bus being ‘somewhere’ in the cloud, I can read the temperature in my study on my Band where ever I am in the world. And while that may not be the most useful thing to do, I actually have used this contraption for real when I was on holiday in Germany for the past 1.5 weeks - in stead of a fan, I connected a spotlight to it, enabling me to turn on a light at home at random times in the evening, in order to confuse potential burglars. Like I said,Windows 10 CoreIoT will always try to keep the default app running - after there's a power failure or a crash, it automatically (re)starts that app. A very useful feature when you are hundreds of kilometers from home and cannot hit a reboot button.

How this will be blogged
As this is quite a big project, I have decided to split the explanation into six blog posts:

  1. Idea, architecture, hardware shopping list and hardware configuration
  2. Using an Azure Service Bus queue for two-way communication between IoT devices
  3. Measuring temperatures using an UWP on a Raspberry PI 2
  4. Controlling a fan using an UWP on a Raspberry PI2 remotely
  5. A client app to show temperature data and control a fan
  6. A Microsoft Band client to read temperatures and control a fan

The idea I just described, so now we go on with the architecture

Architecture
For my previous IoT project - displaying heart rates using an LED connected to a Raspberry PI2 - you might recall I used an Azure hosted Signal/R Hub. This time, as I already said, I decided to go with a queue on an Azure Service Bus. Signal/R worked pretty well in the previous setup, but it has a few disadvantages:

  • It requires you to deploy a web site, while the infrastructure for a Service Bus is 'hosted' by Azure itself.
  • Signal/R signals can only be delivered real time - that is the nature of Signal/R. If you missed it, you missed it. Tough boots. A queue makes it possible to receive data for a little while after it's been sent.
  • Security is a bit iffy - everyone who knows the address of my previous Signal/R hub solution can listen in on the data. Of course, I can encrypt that, or do access security - it's all kind of a hassle and it feels a bit roll-your-own.

There is also a disadvantage - unlike with Signal/R, there is basically only one client possible - that is the nature of a queue. If a client picks up the message, it's removed from the queue. A second client listening won't get it. So a 'broadcast' scenario is not possible. But since this is exactly what I wanted, this suited me perfectly. And my good friend Matteo Pagani from Italy had played with if before, and was kind enough to provide me with some starter code so I could go off to a flying start.

This is a high level overview of the setup:blogplaatjeCalling this 'architecture' is a bit rich I think, but it is intended as a global overview. Although it is not entirely correct, as this picture suggest signals go between phone and PI2 (and back) over a single channel, while in fact there are two queues - one for each direction. Temperature data goes from PI2 to phone over one queue, the command to toggle the fan over the other.

Contrary to most of my demo solutions, this is a more architected solution. It uses separate components connected by dependency injection, and the Windows 10 (mobile) client is a fully fledged MVVMLight app. This is because I wanted to show a little more of how to do things in a more robustly architected way. It also makes it easier to split the blog post into manageable pieces. This is not just a simple demo - it's a complete setup.

The demo solution contains the following projects:

  • TemperatureReader - the CoreIoT UWP app running on a Raspberry PI2 that actually reads the temperature data and displays it on a screen - if one is attached, sends data over the Service Bus and waits for commands to switch the fan on or off. Or actually, just the very limited UI that bootstraps the whole process - all the logic is in
  • TemperatureReader.Logic - contains all of the logic of reading temperature, flashing the LED and controlling the relay using the GpioController class.
  • TemperatureReader.ClientApp is the Windows 10 UWP application that acts as intermediary between the Band and the Raspberry PI2, listening to the signals coming from the PI2 and acting on commands and/or event from the Band. It has it's own user interface to show data and initialize the Band.
  • TemperatureReader.ServiceBus code handling communications via the Azure Service Bus.
  • TemperatureReader.Shared - contains the data objects that are shuttled over the Service Bus, as well as a global definitions class that defines pins used on the bread board, Azure access keys, and stuff like that - because I don't like magic strings and numbers.

Hardware shopping list
To run this project, you will need the following hardware:

  • 1 Raspberry PI2 running the latest Windows 10 CoreIoT build
  • 1 Microsoft Band
  • 1 device running Windows 10 (mobile or otherwise - as long as a Band can be paired to it)
  • 1 Keyes two-color Common-Cathode LED 1
  • 1 Keyes Analog-temperature sensor 2
  • 1 ADC0832 analog-digital-convertor 3
  • 1 Keyes SRD-05VDC-SL-C switch 4
  • 1 breadboard + flat cable connecting it to the Raspberry PI2
  • 14 connection wires (I hope I counted them correct ;) )
  • 3 barrier strip units 5 (The things we call ‘kroonsteentjes’ in Dutch)
  • 1 piece of mains cord
  • 1 mains plug
  • 1 mains socket plug
  • Some duct tape

Pictures of some assorted items:

ledtemperaturesensoradconverterrelaykroonsteentje

Configuration
A word of warning: the hardware configuration uses a relay switch to control mains power. Depending on where you live, that's between 100 and 250 Volts. We are not talking battery power here - this is the stuff that comes out of your wall plugs, drives the washing machines, refrigerators, air conditioners and whatnot, has serious oomph behind it - and can seriously hurt you if you mess around with it. In my sample I have cut a mains cord, reconnected one part via the relay and reconnected the rest using barrier strips. I sealed the connections using duct tape. At the ends of the mains cord are a mains plug and a main socket, so it can be used to control any mains power driven device. Be sure that you are careful with live wires and be aware that whatever I show you most likely would not get approval from a skilled electrician. If you re-create my setup with your own hardware, I cannot accept any responsibility for things going wrong. I also strongly suggest not letting the setup connected to the mains power unsupervised. This is a test/demo project, not a production unit.

The LED
This is an easy one. I have connected "R" to GPIO12, "Y" to GPIO16, and "G" to GND (of course).

The SRD-05VDC-SL-C switch
A bit more complicated, as the are no markings on the pins of this device. If you hold it the way that you can read the text on the blue block and the pins are sticking out to the right (as in picture 4) I have connected the top pin to GND, the middle pin to 5V,  and the bottom pin to GPIO18.

On the other side, the part with the screws on it - I connected the mains wire. I cut this first, then reconnected to mains using three terminal strip units - an sealed the stuff with duct tape. As already stated - follow this advice at your own risk. Basically one wire goes straight trough, the other part goes through the switch. Now it's not easy to see, but if you hold the switch like displayed on picture 4 (and below), you will see screws on the left side, and you  can just about read "NO" under the top screw, and "NC" under the bottom screw. This stands for "Normal Open" and "Normal Closed". You fix one of the mains wire to the NO screw, and the other under the middle screw.

imageimage

The Analog temperature sensor
I have connected the middle pin to 3.3V, the "-" pin to GND, and "S" pin to 2 of the AC-converter (see below). That converter is the hardest part.

The ADC0832 analog-digital-convertor
I'll be the first one to admit that I actually have no idea how this works, I nicked the idea from the Sunfounders manual. I understand the principle of an A/D converter, I just have no idea why it needs to be connected in this specific way, and I understand even less of the programming 'sequence' (that will be described in a later post) imagethat goes into it. Anyway, this A/D converter is a chip and if you hold it the way that you can actually read the text on it, the pins are numbered this way. Why? I really don't know, having no formal background in electronics. Now this pins also have labels attached to them which are:

1 = CS
2 = CH0
3 = CH1
4 = GND
5 = DI
6 = DO
7 = CLK
8 = VCC

These names we will see back later in the sample solution. So, more or less following lead of the Sunfounders manual, I made the following connections

  • 1 to GPIO5
  • 2 to the "S" pin of the Analog temperature sensor
  • 3 to nothing
  • 4 to GND
  • 8 to 3.3V
  • 7 to GPIO6
  • 5 and 6 to GPIO13

Running the sample solution
If you want to run the sample solution, you will at least need to

  • Create an Azure Service bus
  • Paste the key into Settings.cs in TemperatureReader.Shared
  • Deploy the TemperatureReader app on a Raspberry PI2 running Windows 10 CoreIoT with all the named hardware attached
  • Deploy the TemperatureReader.ClientApp to a Windows 10 device with a Microsoft Band to it.

The next episode in this series will explain how the Azure Service bus is utilized as an IoT communication conduit.

03 September 2015

Windows 10 maps part 5 - styles and 3D

Intro
In part 5 of this series I will show two seemingly unrelated things - the map "styles" and 3D maps. From a code perspective this is, just like last time, a post that is pretty light on code, but it contains some of the most exiting new features of the Windows 10 map control.

Styles? What Styles?
Map data differs from ordinary tabular data in the sense that it needs reference data - a backdrop map - to make it intelligible. A map of parking garages on a otherwise black screen is almost totally useless - a map of parking garages on top of a topographical map makes it possible for the human eying it to connect the data to the real world (and decide the trip is too far or not). This is where the map's Style property comes in. Personally I fear the word "style" when used in a map context will not immediately conjure up the right image in the uninitiated developer's mind. 'Styling' usually refers to changes to the layout of some screen element  -think of inline CSS styles, or the XAML Style element. Styling in the context of the Windows 10 UWP map refers to the kind of data displayed as backdrop on the map, and to an extent how the data is interpreted.

A map's Style attribute may be set to a value of the MapStyle enumeration, which has the following members

public enum MapStyle
{
  //
  // Summary:
  //     A style is not specified.
  None = 0,
  //
  // Summary:
  //     A road map.
  Road = 1,
  //
  // Summary:
  //     An aerial map.
  Aerial = 2,
  //
  // Summary:
  //     A hybrid map that combines an aerial map with roads.
  AerialWithRoads = 3,
  //
  // Summary:
  //     A terrain map.
  Terrain = 4,
  //
  // Summary:
  //     An aerial 3D map.
  Aerial3D = 5,
  //
  // Summary:
  //     A hybrid map that combines an aerial 3D map with roads.
  Aerial3DWithRoads = 6
}

and since the Windows Development Team has been so kind to add comments to the code explaining each member's function, I thought it best to include that verbatim in this blog post. And now the link with 3D immediately becomes clear: styles Aerial3D and Aerial3DWithRoads kick the map into 3D mode. But let's keep the best for lest, and have a look at the 'ordinary' 2D styles first.

MapStyle.None
This may seem like the oddest of styles, but this indeed creates a map with no backdrop at all. I have just stated that a map like that is completely useless, but all you are doing now is instructing the map to draw all shapes (that is, lines, polygons and icons) but no backdrop because you don't want to use the available standard data - for instance, because you want to use a custom backdrop map. Examples of this will be handled in the last post of this series.

MapStyle.Road
This is the default map style showing roads and labels, and in the sample app it looks like this
image

MapStyle.Aerial
This looks like this - it shows a map with aerial imagery in stead of a 'normal' map - without any labels. For mainstream app development you will not be using this map very much I think, unlike the next one
image

MapStyle.AerialWithRoads
This shows the aerial map with a road network and name labels superimposed. image

This definitely hasit uses, especially in tourist and 'getting to know the environment' targeted scenarios, but a little caveat is on it's place: while it looks 'more cool' than an ordinary topographical map, it it has two distinct disadvantages:

  • For navigation purposes, a topographical map wins heads down from a imagery map because map makers over the ages have perfected the art of emphasizing what's important to get from a to b, and on imagery maps this is impossible.
  • Image maps are way bigger and do not work in an offline scenario. When Windows offer you the possibility to download offline maps, that means the road maps, not the imagery maps. Downloading an imagery map for the whole of the Netherlands - spanning a meager 300x200 km - alone would probably eat more storage than my 1520 has aboard, while that same phone now holds the road maps for all of the Netherlands, Germany, Belgium and Washington State - and all that map data barely makes a dent in available storage. This is because road maps can be (at least partly) stored as very efficient so-called 'vector graphics', while imagery is just bitmaps - essentially a digital photo - and that gets big very fast. So be aware - Windows does cache this kind map imagery to optimize bandwidth usage, but it does not pre-download it so relying on this in a potential offline scenario may result in a degraded user experience.

MapStyle.Terrain
This gives you a kind of faux-3D view of the maps,using shading techniques. If I were to use this on my standard location - around my home in the Netherlands - you would see not much of a difference, as height differences in the Netherlands for most parts are measured in mere centimeters, but if I zoom to some more complex terrain in for instance the edge of the German Pfalzer Forest, you get this kind of effect:
image

To show this is not 'real' 3D - if you change the pitch, you don't see any hills appear:
image

Be aware that this kind of data has the same limitations in offline scenarios as aerial maps.

MapStyle.Aerial3D
The previous style, as I said, was a kind of 'false 3D effect'. But if you take the same area as before (Neustadt an der Weinstraße in the German Pfalz) in Aerial3D you get this awesome view of rolling forested hills with houses and road meandering between them. It very much looks like the real thing, standing on a hilltop looking around
image

MapStyle.Aerial3DWithRoads
Essentially the same map as before, but now with a projected road network on top of it, as well as 3D labels that look as if they are on edge, so you can always read them.
image
This is by far the most mind boggling map mode of all - it is a very visually powerful map, gives a real sense of how things look in real life, and you can put your own data on top of it, too! I think this is what GIS will look like in the very near future. And of course, this also works on Windows 10 mobile, it's not called a Universal Windows App for show:
image

Although, in all honesty, the effect is not as profound as on a bigger screen. Be aware, once again this uses data that cannot be pre-downloaded.

Setting styles
The code for setting the styles is very simple. I made drop down with texts in it that match the MapStyle enum values, and when the user selects a different map style, this code is executed:

private void MapSelectionChanged(object sender, SelectionChangedEventArgs e)
{
  var selectedItem = e.AddedItems.OfType<ComboBoxItem>().FirstOrDefault();
  if (selectedItem != null)
  {
    MapStyle mapStyle;
    if (Enum.TryParse(selectedItem.Content.ToString(), out mapStyle))
    {
      MyMap.Style = mapStyle;
    }
  }
}
As you can see this is not quite rocket science.

3D data
I actually visited this before, when it first surfaced in Windows 10 SDK build that appeared around April 1st.If you start the sample app and:

  • set pitch to zero (so you have an ordinary maps that you look upon from above),
  • then go back to initial location
  • then press "draw points" a couple of times again
  • set "icon collision" to "show"
  • imagethen select Aerial3DWithRoads
  • and finally set the pitch again back to 75, not using my slider but the canvas control

You will see that that the MapIcons actually float in the air

image
The way this is achieved is actually very simple. In part 2 of this series I showed you needed a Geopoint to place a MapIcon on the map. A Geopoint needs to be created from a BasicGeoposition like this

new Geopoint(new BasicGeoposition { Latitude = 52.181427, Longitude = 5.399780 });

As I already wrote in part 2, BasicGeoposition also has an Altitude property, so setting an altitude to a MapIcon is a simple as this:

new Geopoint(new BasicGeoposition 
    { 
Latitude = 52.181427, Longitude = 5.399780, Altitude = 10 });

Be aware that while Latitude and Longitude are in degrees, the Altitude is simply in meters - thank heavens it's not in feet :), so this MapIcon will appear 10 meters up in the air. In my code I am simply giving random values between 0 and 1000 meters - you can find that code in PointList.GetRandomPoints.

Concluding remarks
With these new capabilities mapping on Windows has made a major leap forward in ways to present map data in a both attractive and informative way, that can be controlled with just a few properties. Be aware though of the limitations in offline scenarios - always make sure your app still works on 'just road maps' to make sure the users still can use your app when he/she is out and about and does not have the best (if at all) network connection

01 September 2015

Microsoft are not spying on your hard disk because there is nothing to gain - and everything to loose

There is a debating technique that is called "reductio ad absurdum" which demonstrates the validity of a statement by proving that the opposite is impossible (absurd). A common example is "rocks have weight, or else we should see them floating in the air". Without going into technical details, I state that Microsoft are not spying on your hard disk, because

  1. they have nothing to gain from the act itself
  2. there is no way they could prevent destroying themselves in the process - and they know that.

Let's just assume, for the sake of argument, that Microsoft are indeed the bunch of evil scientist some people seem to think they are. Spying on you would require some data gathering process and some process of transmitting data to Microsoft, using your own network connection. Agreed? Well then, with Windows 10 running on 75 million (and counting) machines, a substantial number of those owned by clever d- I mean smart persons - who know very well how to operate network analyzing tools like WireShark, there is no way in Hades they could keep the data transmitting part of that process secret forever. Any spying tool included in Windows 10  will be found. Sooner or later. By those smart people. By anti virus software makers. Or it will be revealed by a whistleblower. Whatever. When - not if - such a spying tool would be discovered, Microsoft would receive crackdowns from both the USA and EU governments that would make their experiences with the DOJ in the bad old days seem like a walk in the park on a sunny day, and they would loose the trust of all their clients overnight. People would stop using Windows, Azure, the whole kit and caboodle'. And what, exactly, would Microsoft have to gain? Your local games score is not that interesting, neither is your local document store. A local store of illegal imagery, music or movies may be of interest to the law, but not to Microsoft - whatever's on your PC is your responsibility.

The only 'spying' that is going on is some telemetry on apps or parts of Windows that run into trouble and report whatever happened when things went South back to Microsoft (or the app developer) to make it easier to fix those bugs. If you opt in for customer improvement programs (and I almost always do) some usage patterns may be transmitted. This is not new, telemetry has been part of the last couple of Windows releases and this is all anonymously, for the same reason - should Microsoft ever be caught red-handed spying on individual users, they would receive hell from all directions, and rightly so.

So why would Microsoft spy on your hard drive? There is nothing to gain, and everything to loose. Microsoft are in the business of making great software and services and making money with that - preferably lots, and they are pretty good and successful at that. They are not into spying, because they won't make money from the act itself but they would put nearly all of their existing money makers in very real danger. It would be just absurd to do that. It would not make sense even when they were indeed an 'evil spying company', which they are not. They are making billions in cloud services, a business primarily based on technical excellence, high availability and above all trust. To put it very bluntly, whatever is on your hard drive cannot possibly be worth violating that trust. You are simply not that interesting - or profitable.I am sorry to have to put it like that, but that is the simple truth.