ESP8266 running on batteries

If you haven’t yet heard about the ESP8266 then it’s time for you to wake up and get serious! This little beauty is a seriously low-cost WiFi chip with a full TCP/IP stack and microcontroller made by ExpressIf. It sports 16 GPIO pins, SPI, I2C, UART, and even has a 10-bit ADC for good measure. And the price? Less than $2 on AliExpress! It is the size of a coin, and supports b/g/n wireless protocols. What’s not to love about this thing?

Wemos D1 mini ESP8266 Board Supports Shields with a Temperature ...

The device isn’t particularly heavy on electricity to start with, but it can pull as much as 200mA when it’s transmitting over WiFi, and generally around 75mA just being awake.

If you plan on running it on batteries, you’ll soon find that they only last a few days before the thing dies down!

 

Enter Deep Sleep Mode

Luckily, there is a very nice way to help on this. You see, the device has a hibernation mode (among other modes, see the full list here) that allows it to drop to as low as 60 microAmpere, and it is really easy to do it. Here are the relevant bits of code to make it happen (using Arduino Sketch or Visual Studio with VisualMicro extension:

extern "C" {
#include "user_interface.h"
}

void setup()
{
    initSerial();
    initWifi();
    initSensors();
}

void loop()
{
    // Gather sensor data
    // Transmit sensor data over wifi somewhere

    Serial.println("Entering deep sleep mode");

    auto fiveMinutes = 5 * 60 * 1000000;

    system_deep_sleep(fiveMinutes);
}

At the top, we’re referencing a C-library, which is why it is wrapped in the extern scope. Fail to do this, and it won’t compile due to types being different and other woodoo.

The ESP8266 enters a state where everything is shut off except for the realtime clock to hit the 60µA. After the clock fires up again, the device essencially reboots, running setup() again before entering loop().

NOTE
This does NOT work unless you create a short circuit between GPIO pin 16 and the RESET pin on the device. The clock needs this wire in order to wake itself up after the timer ends. So remember, there is a hardware change included in getting this right!

Diagram

Conclusion

Setting the ESP8266 in deep-sleep mode means that you can start to make battery driven solutions that will last for months instead of days. At an average of 75mA in normal mode, a 2450ma Eneloop would last around 32 hours or less on battery power, but on the same battery, you should be able to expect months (depending on how hard you drive the WIFI and sensor power consumption ofc.) Also remember that the power converters from battery to 3.3v aren’t perfect, giving you at best 85% of stated battery capacity, but all in all, it’s a good and handy thing to know about!

Profectus Est!

(It is started!)

Project Water my Plants has begun. This blog post marks the arrival of the first bits of electronics, and provides a simple overview of how the getting started with gadgeteer felt like.

White stripe spider plant
Image 1: The victim: A white stripe spider plant(Chlorophytum comosum ‘Vittatum’)

My box of Gadgeteer devices has arrived. I’ve found a suitable plant to experiment with and all of the software required to get started is now installed in two places (on my desktop and on my laptop (for field experimentation). As you can see from the brown bits, this plant is already suffering, and requires immediate attention of the highest technical quality to survive…

Overview of the project

The project has been set up using Visual Studio 2012 and will be managed by Team foundation Service, which will also function as my source control provider.

 Initial Solution Layout
Figure 1: Overview of project layout

The project structure follows the typical N-layered approach as seen on the image above. Within folder 10.10 (Application/Micro Framework) is where the electronics software are made – the rest of the folders are hosts to the Web page and Web Services. The Specifications folder contains screenshots and some frameworks for running the project in a BDD harness using a combination of SpecFlow and CasperJs 

Getting started with Gadgeteer

DSC_8618
Image 2: The Gadgeteer Moisture sensor half buried in the plant soil

Installing the .Net gadgeteer project was straight forward, except for a couple of things:

  • You should install the entire 4.2 SDK, and then upgrade to 4.3
  • There is a Visual Studio 2012 compatible Core + Templates for Gadgeteer that you need to install once you’re done installing the 4.2 stuff, otherwise, you won’t be able to see the Gadgeteer application project types.

     

    Once installed, creating the project was as easy as adding a new project to the solution, choosing Gadgeteer Application and following the wizard:

    Gadgeteer Wizard
    Image 3: The first page of the wizard asks what type of mainboard you have

    The wizard starts by asking what type of mainboard you have, and then proceeds to create a diagram where the mainboard is visualized. From there, it is as simple as just dragging the components you want from the Toolbox onto the designer, and connecting them by clicking on the gates and drawing a line:

    Gadgeteer Designer in VS2012
    Image 4: Using the designer tool to drag the components and connect them to the board

    Auto-generated code

    Every time you save the designer, the auto-generated partial class Program is updated with the new components and port assignments. The generated code is clean and easy to understand. No cluttering or cryptic names here. The module names are default the same as the module type.

    OGadgeteer Designer Generated Code
    Image 5: Designer-generated code

  • Measure My Plant

    The first batch of electronics to arrive were needed for my first application, MeasureMyPlant.exe which is a device application that is going to do two things:

    1. Take readings of the environment that the plant is in (moisture, light, temperature)
    2. Transmit data over wifi to a cloud service in Azure

     

    Only part 1 was done in this stage, because I waited with the more expensive WiFi component to get a cheap proof of concept going. It turns out that I should’ve ordered everything at once. The electronics simply worked! Within 5 minutes of typing, I had the following program running on the Hydra board:

    MyFirstProgram
    Image 6: My first running program on the hydra board

    Time to order some more stuff!

    I will now proceed with some of the more expensive modules. While I await the arrival of these, I will be working on the website. There may be a blogpost or two about that soon…

    For now, a few more images of the protagonists of this blog post:

    DSC_8625
    Image 7: The modules used in this blog (click for larger image)

    DSC_8620_Snapseed
    Image 8: My Fez Hydra mainboard with all the connection ports(click for larger image)

    Structuremap: Singleton class with multiple interfaces

    In a recent project, I had the need to implement multiple interfaces in a single Repository class

    public class UsageStatisticsRepository : DbContext, IApiKeyCounter, IIpAddresssCounter
    {
       
    // …
    }

    We use Structuremap as our IoC container, and attempting to configure the two interfaces as Singletons gave us two instances (naturally), once for each interface.

    The solution, was to use the not-so-obvious keyword Forward in order to re-use the Singleton instance for another interface as so:

    public class DigitalDiasRegistry : Registry
    {
        public DigitalDiasRegistry()
        {
            For<IApiKeyCounter>().Singleton().Use<UsageStatisticsRepository>();
            Forward<IApiKeyCounter, IIpAddressValidator>();
        }
    }
    

     

    With that, the problem was solved, and only one instance occured. Since I fiddled some time to figure this out, I thought sharing it would help someone else.

    Hett smilefjes

    Using Structuremap to resolve ViewModels

    One of the things I find myself doing over and over again when working in xaml-based applications is to create a ViewModelFactory based on Jeremy D. Miller’s StructureMap.

    All my ViewModel classes are based on a class BaseViewModel:

        public class BaseViewModel : INotifyPropertyChanged
    

    The fun, of course, begins when your viewmodels need to know about other viewmodels. Lets say, for instance that your main view contains a Container control in which you would like to swap views in. Using structuremap, it is easy to inherit the Registry class in order to stitch together associations between views and models:

    public class ViewModelsRegistry : Registry
    {
        public ViewModelsRegistry()
        {
            Rig<MainWindowView, MainVindowViewModel>(Registered.MainWindow);
            Rig<TrioEventsView, TrioEventsViewModel>(Registered.TrioEvents);
            Rig<NewsContentView, NewsContentViewModel>(Registered.NewsContent);
        }
    
        private void Rig<TControl, TViewModel>(Registered name) 
            where  TControl : ContentControl where TViewModel : BaseViewModel
        {
            For<ContentControl>().Singleton().Use<TControl>().Named(name.ToString());
            For<BaseViewModel>().Singleton().Use<TViewModel>().Named(name.ToString());
        }
    }
     

    The Registered reference is an enum that I use to keep tabs on what views/viewmodels that are implemented:

        public enum Registered
       
    {
            Unknown = 0,
            MainWindow,
            TrioEvents,
            NewsContent,
            Locations
        }

    As you can tell, the ViewModelsRegistry uses ContentControl as it’s container type. This makes it  compatible with all derivates, including Window and UserControl.
    Following the factory pattern, the result follows:

    public static class ViewModelFactory
    {
        public static void Initialize(Registry registry)
        {
            ObjectFactory.Configure(o => o.AddRegistry(registry));            
        }
    
        public static ContentControl Get(Registered name)
        {
            var control = ObjectFactory.GetNamedInstance<ContentControl>(name.ToString());
            control.Loaded += (s, e) => {
                control.DataContext = GetDataContextFor(name);
            };
            return control;
        }
    
        public static BaseViewModel GetDataContextFor(Registered name)
        {
            return ObjectFactory.GetNamedInstance<BaseViewModel>(name.ToString());
        }
    }
    
     

    The ViewModelFactory basically leans on structuremap providing the method Get() that stitches together a view and it’s model. One example of such use:

     

            public void LoadEvents(object dummy)
            {
                SetViewModel(Registered.TrioEvents);
            }
    
            private void SetViewModel(Registered name)
            {
                if(!_loadedControls.ContainsKey(name))
                    _loadedControls.Add(name, ViewModelFactory.Get(name));
                    
                CurrentContent = _loadedControls[name];
            }
    

    In the above snippet, taken from the MainWindowViewModel,  LoadEvents is bound to a button click on the Main Window. Once clicked, If I haven’t already loaded the control, I use the factory.Get() method to create a UserControl with initalized datacontext, before I finally set the ContentPresenter (CurrentContent) on the Main window viewmodel.

    The factory can easilly be expanded to swap out datacontexts, provide different views. This blog post is mainly about using structuremap to make it happen.

    Jeg bare tøyser

     

    A good basis for unit testing

    Over time, one developers techniques and habits that “just work”. In this post, I would like to share with you a set of base classes that I’ve been using and refining over time. They make my Unit Test writing a little more efficient and easy on the eyes.

    The base of the base

    I often start a new software project by setting up some form of base unit test class with functionality that I know I will be using, such as using embedded resource documents, various kinds of verifiers, test names etc. I usually name this class “BaseUnitTest”. This blog post will not be focussing on this base of bases, but to give you an idea, this is roughly how it starts out.

    public class BaseUnitTest
    {
        private Assembly _testAssembly;
        public EmbeddedResourceManger ResourceManager { get; internal set; }
        public IoVerificationManager IoVerifier { get; internal set; }
    
        public BaseUnitTest ()
        {
            _testAssembly = Assembly.GetCallingAssembly();
            ResourceManager = new EmbeddedResourceManger(_testAssembly);
    
            IoVerifier = new IoVerificationManager();
        }
    }
    

    I usually add on methods to this class in the form of Verfiers of different sorts. A handy base class for your Unit  Tests is not the scope of this blog though…

    Wrapping AutoMocking and Instance creation with BasedOn<T>

    Now follows the real nugget. A base class for your unit tests that uses StuctureMap’s AutoMocker to construct a nice, testable innstance of the class under test.

    [TestClass]
    public abstract class BasedOn<TInstance> : BaseUnitTest where TInstance : class
    {
        public MoqAutoMocker<TInstance> AutoMocker { get; internal set; }
        public TInstance Instance { get; internal set; }
    
        [TestInitialize]
        public void RunBeforeEachTest() 
        {
            AutoMocker = new MoqAutoMocker<TInstance>();
    
            OverrideMocks();
    
            Instance = AutoMocker.ClassUnderTest;
    
            ExecuteBeforeEachTest();
        }
    
        public Mock<TInterface> GetMockFor<TInterface>() where TInterface : class
        {
            return Mock.Get(AutoMocker.Get<TInterface>());
        }
    
        /// <summary>
        /// Use this from your OverrideMocks() method so that all replacements are made before
        /// the Instance is created
        /// </summary>
        public void Replace<TInterface>(TInterface with) where TInterface: class
        {
            AutoMocker.Inject<TInterface>(with);
        }
    
        public virtual void OverrideMocks()
        {
        }
    
        public virtual void ExecuteBeforeEachTest()
        {
        }
    }
    
    

    How it works

    The BasedOn<T> class defines an AutoMocker for the class that will be tested as well as a member named ‘Instance’ that is used in the unit tests. The method RunBeforeEachTest() is attributed with [TestInialize] so that it will execute prior to each unit test.

    Note: Because this attribute is used in the baseclass, you cannot re-attribute any method in your derived unit test class. That is why there is a method named ExecuteBeforeEachTest() that you can override to accomodate your Unit testing needs.

    If you need to prepare a special Mock or stub into the class you are testing, you can override the method OverrideMocks() in your unit test class – this method is executed just before the Instance member is created. The method Replace<T>(T with) is meant to be used for this very purpose.

    Example of use

    The class PersonManager is a business layer service that handles Person objects. In the following example, we are setting up a Unit test to ensure that person objects that do not have surnames cannot be updated. Using the BasedOn<T> base class:

    [TestClass]
    public class PersonManagerTests : BasedOn<PersonManager>
    {
        [TestMethod]
        public void UpdatePerson_PersonHasNoLastName_DoesNotInvokeRepositoryUpdate()
        {
            // Arrange
            var testPerson = new Person();
    
            // Act
            Instance.UpdatePerson(testPerson);
    
            // Assert
            var repoMock = GetMockFor<IPersonRepository>();
            repoMock.Verify(o => o.Update(testPerson), Times.Never());
        }
    }
    
    In the next example, I am preparing the repository to throw an exception to verify
    that an exception uses the logger interface:
     
    [TestMethod]
    public void Create_RepositoryThrowsException_ErrorMessageIsLogged()
    {
        // Arrange
        var somePerson       = new Person();
        string exceptionText = "Something really bad just happened";
        var someException    = new Exception(exceptionText);
        var repoMock         = GetMockFor<IPersonRepository>();
    
        repoMock.Setup(o => o.Create(somePerson)).Throws(someException);
    
        // Act
        Instance.Create(somePerson);
    
        // Assert
        var loggerMock = GetMockFor<ILogger>();
        loggerMock.Verify(o => o.LogException(exceptionText), Times.Once());
    }
    
     

    The magic performed by AutoMocker combined with a relatively simple base class has helped me immensly in making my tests more readable – and for others to read! At the time of this writing, AutoMocker supports Moq, Castle, and TypeMock.

    For those classes that you do not want automocked, you can always bypass the BasedOn<T> class and inherit the BaseUnitTest directly for access to the test helper methods and verifiers.

    Smilefjes

    Smart Reflection with dynamic type in .Net 4.0

    A collegue of mine at my current project in NRK showed me how to use the dynamic keyword in C# to perform dynamic casting from a base type to a derived type. I just had to share!

    The example starts with the following hierarchy of types:

    public class Person{
    }
    
    public class Police : Person {
    }
    
    public class Fireman : Person{
    }

    The heart of the matter

    Typically, you will have a controller/manager class that calls different workers based on the type of object at hand. In ASP.NET, for example, you may have a controller that will return a different rendering of a view based on the 
    type of person to render. In its simplest form, the following 3 functions could form such a controller:
    public void Draw(Person p) {
        Console.WriteLine("Drawing a generic person");
    }
    
    public void Draw(Police police)    {
        Console.WriteLine("Drawing the police");
    }
    
    public void Draw(Fireman fireman) {
        Console.WriteLine("Drawing a firefighter");
    }
    Easy peasy, you say and proceed to write some test code: 
    // Arrange
    var people = new List<Person>{
        new Person(),
        new Police(),
        new Fireman()
    };
    // Act
    foreach (Person p in people)
        Draw(p);
    Do you see the problem?

    …the above code will issue 3 calls to the function that draws the base person type. The other two functions are never called. This is self-explanatory, since the foreach loop defines a Person reference. Using var has the same effect, because it is getting populated from a list of Person objects. The compiler simply does not see the Police or Firemen objects.

    Now, if you change the foreach-loop to this:

    // Act
    foreach (dynamic p in people)
        Draw(p);

    (use of the dynamic keyword requires that you add a reference to Microsoft.CSharp and System.Core)

    The dynamic keyword is strongly typed, but, the compiler is told that the type of object, p will be determined at runtime, and not during compile time, thus each person object in the list will become a strongly typed police and fireman during runtime, similar to dynamic_cast in c++ (damned near identical if you ask me!)

    Concerns

    Any type of run-time-type checking will involve reflection in some form or another, however, Microsoft has gone a long way in ensuring that this is second-generation reflection, using a funky named tri-state cache to keep things fast. Another concern, of course, is that you can always cast any type to dynamic without compile-time checking, so you basically want to ensure 100% coverage by unit tests as well as ensure that the unit tests will catch type-mismatches.

    Conclusion

    Using the dynamic keyword will clean up the code considerably at the cost of having to keep in mind that you wil have no compile time checking of any lines of code that involve the dynamic keyword, so make sure you write those unit tests. Additionally, because this is run-time checking, you should consider other options if you depend on faster code, but for most of your code, the performance impact is non-measurable.

    More on dynamic keyword here – Official documentation on MSDN

    Dissecting the C# 4.0 Dynamic programming – Good article about the inner workings of dynamic