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!

Getting the newest entry from Azure Table Storage

Sometimes, all you want is to be able to quickly get to the last value of a sensor, or the freshest product in your Azure Table without having to do complex artsy queries to achieve that result. Trouble is, querying against Azure tables does not give you a Last() option, so we have to get sneaky!

Turns out, Azure Tables are ordered by their RowKeys, which are indexed, so we’re in luck. The challenge is that you need to input a string that is ever descending in value, so that the newest elements are always fresh on top. Here’s a trick to do just that:

DateTime to the rescue!

The simple trick is to use the DateTime.MaxValue property, which gives us the highest possible value of DateTime. Then we convert that to ticks in order to get a huge number. Subtract the DateTime.Now value from that, and what we end up with is a large enough number to use as a RowKey that is “ever descending”:

image

The string formatting is just to populate the value with 19 digits.

The RowKeys are now stored in an ever descending order, here’s a snip of a table I’m storing some sensor values in (using Azure Storage Explorer):

image

On the reading side, you can now simply execute your query knowing that the order of the returned values will always have the first item as the last inserted:

image

 

Learn it, love it, live it!

  • Professional resume and cover letter
  • Bruk av lagring i skyene

    Her kommer et blogginnlegg på norsk!

    Jeg har laget en liten video som viser en øvelse jeg gjør for deltakerne på den månedtlige Microsoft Azure Camp. Dette er et månedtlig event på ca. 3 timer der utviklere kan komme på besøk til meg og få litt hands-on erfaring med å lage et program som bruker lagring i skyen.

    PartyImageUploader

    Programmet går ut på å implementere en automatisk opplasting av festbilder til Microsoft Azure, slik at disse senere kan vises i f.eks. en website som er laget for formålet. Øvelsen er rask å skrive, og fungerer flott som en kode kata til de som trenger å styrke seg på bruk av cloud tjenester.

    YouTube Video

    Til formålet har jeg laget en 20 minutter lang video hvor jeg bygger løsningen fra scratch.

    Viktig:

    Velg 1080p eller 720p for å kunne lese teksten i denne videoen!

    Sees best i fullskjerm på 1080p eller 720p

     

    Tilbakemeldinger og forbedringsforslag mottas med glede, enten på youtube direkte, eller her

    Smilefjes

    Pedro

    Faster and Slower

    Growing concerns about the direction of Xaml-based applications

    Microsoft, what the hell do you think you are doing by diverging WPF, Silverlight and Silverlight for WP7?? None of those 3 destination platforms have any solid foothold as of yet. By making different options of XAML available in different destination platforms, you’re only doing one thing: pissing off developers. Stop doing that, this is really simple:

    WPF

    imagesCA28TSXTWPF should be the mother of all xaml based apps and have every available technology to it – including webcam support as in silverlight, MEF, etc. WPF needs to be that “unlimited” target platform from which both silverlight and WP7 pick their features from.

    Silverlight

    imagesCA197ISS

    Why oh why can I not use data triggers in SL? What is the reasoning for it? I know MS has “shifted focus” for Silverlight. This, in my ears, is bull. Silverlight on iOS and Android will give developers reason to use it. WPF alone cannot succeed as the only xaml-based platform, and SL makes sense for servicing the current craze of tablets and smart phones. Very few people will disagree when I say that MS powered devices (tablets and phones) are lagging far, far behind. For SL to be a success, it needs to penetrate iOS and Android. End of story. rest is just bull.

    Silverlight for WP7

    phone7I accept that SilverLight for windows Phone 7 will offer different capabilities from Silverlight as a xap, but what I don’t get is why this version of Silverlight has to be a framework behind the current release of Silverlight web?? It makes no sense, whatsoever to keep developers in confusion station by not holding back releases until the technology is ready on all platforms!

    Converge now!

    What Microsoft needs to do, is to hold back releases, so they can do a unified XAML platform upgrade targetting windows, SL and WP7 with the same developer options and syntax. No data trigger support for WP7 means dont release it for Windows or SL either! This is FAR better for developers than the mess you’re giving us now! XAML as a developer platform, needs a unified version number, we dont want to have WPF for .Net 4.0, Silverlight 5.0 for web and SL 3.5 gutted for WP7. 

    So, where was I?

    You may have notice that digitaldias was down for a week or two.

    I’ve been using an SHDSL line (Single-Pair High-speed Digital Subscriber Line) for the last 6 years, giving me a whopping 2Mbit in both directions!

    Recently, though, I’ve been on the lookout for higher download speeds, as iPads, laptops, and even the PS3 consume more and more information from the web. When I was offered the option of 20Mbit down, and 1Mbit up for much less moolah, I took it.

    My blogs will load at half speed (as if you care!), but then again, I dont connect back to my office over VPN anymore, so I dodn’t have any good excuse to pay that much for a decent speed out anymore.

    I still want higher output speed, for using skype in HD, but that’ll have to come when the prices (and availability) fits.

    Logo

    My ISP, Nextgentel delivered fast and reasonably priced this time. For that, they get a nice, well deserved kudos from me Smile

    TDD: Using databind to object for the ultimate tdd exerience

    Figured I need to share with you how I normally go about designing UI, and how I make that design as testable as possible.

    To make things easy, I will use a login screen as an example, since it has few controls, and is relatively simple to follow.

    Sample VS2008 solution can be downloaded here

    The criteria

    • Create a login  dialog with a username, password, OK and Cancel button
    • OK Button is only enabled when both a username and password are set
    • Should be fully unit-testable

    Implementation

    I start by creating an empty solution with my typical folder structure.

    image

    The numbering is just something I add to the folders because I like to have the top-down view. Note that I have a clear separation between UserInterfaces and Presentation:

    User Interface: Dumb dialog, form, or page containing bindable controls that the user interacts with

    Presentation: Smart, data-bindable classes that represent a user interface’s logic and state.

     

    Create a login  dialog with a username, password, OK and Cancel button

    Next, I’ll add the windows forms project to the User Interfaces folder that contains my login dialog, and design our choice login box:

    image

    I am only interested in the design at this stage. Aside from setting the property UseSystemPasswordChar on the textbox for the password, and naturally giving the controls some meaningful names, I do not bother looking at code here.

     

    Preparing to code

    The next bit is half the magic. I am going to create a class to represent my login dialog. By implementing the INotifyPropertyChanged interface (found in System.ComponentModel), I am telling this clas that it can be databound to windows forms, WPF and silverlight controls.

    I begin by adding a Presentation class library to contain the login class, as well as a test project where I can put all the facts related to it:

    image

    The Solution Items folder that you see at the bottom contains the test list and testrunconfig files, it is autogenerated by visual studio the first time you add a test project to your solution.

    • Presentation is a regular class library
    • Presentation.UnitTests is a test project

      Must be fully unit-testable

      In visual studio, it’s hard to write tests for objects that do not exist, this is due to intellisense trying to help you as you go actually turns into something you have to fight. Creating a skeleton Login class makes this process a lot easier.

      Initally, it looks like this:
    public class Login : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler  PropertyChanged;

        public string Username            { get; set; }
        public string Password            { get; set; }
        public bool   OkButtonEnabled    { get; }
    }

     

    The PropertyChanged event is the mechanism used for databinding. More on that later.

    Initially, I am interested in the following behavior from my login class:

    image

    Implementing these tests is fairly straight forward. When done, I can proceed to getting them to pas.

    SIDENOTE: Unsure on how to verify events in a test? here is a smart way to do it:

    [TestMethod]
    public void PropertyChanged_SetPassword_EventFires( )
    {
        // Prepare
        Login login            = new Login( );            
        bool eventWasFired    = false;
        login.PropertyChanged += (sender, e ) => eventWasFired = true;

        // Invoke
        login.Password = _testPassword;

        // Assert
        Assert.IsTrue( eventWasFired );
    }

     

    Back to our Login class, we want the Properties to “announce” that they have been changed,

    this can be done like so:

    public string Username            
    {
        get{ return _userName; }
        set
        {
            if( _userName == value )
                return;
            //TODO: Validate username
            _userName = value;
            NotifyPropertyChanged( "Username" );
        }
    }

    private void NotifyPropertyChanged( string propertyName )
    {
        if( PropertyChanged != null )
            PropertyChanged( this, new PropertyChangedEventArgs( propertyName ) );
    }

    Basically: If I can set the value, I announce it with my event handler. There is no point announcing a value that was never set.

    Finally, the OkButtonEnabled property simply checks the username and password:

    public bool OkButtonEnabled    
    {
        get
        {
            if( string.IsNullOrEmpty( Username ) )
                return false;

            if( string.IsNullOrEmpty( Password ) )
                return false;

            return true;
        }
    }

    I’m a sucker for readability, can you tell? :)

    After a very brief syntax check, I’m done with the Login class for now:

    image

     

    Binding it to the form

    At this stage, I now have a Login form with absolutely no code behind it. Additionally, I’ve created a Login class that announces every property that changes, it is time to bind the two together. The process is simply:

    • Declare the login class as a data source
    • Bind properties from the login class to our form
    • Initialize the binding in the form’s constructor (in the code behind)
    Declare the login class as a data source

    In design mode, bring up the properties of the username textbox, find the databinding section. Since this is the first time we’re doing a data source, I can pre-select the Text property that I want to bind to, and then click Add project data source link

    image

    This brings up the following sequence (I’ll just run through the images, no comments should be necessary):

     

    image

     

     

    image

     

    image

     

    Having completed this process, you can now simply bind the TextBox.Text property to your bound class object with a simple drop-down:

    image

     

    The OK Button requires a special binding, because we want to bind it’s true/false value to the Enabled property, so we open up the Advanced data binding dialog:

    image

    Find the Enabled property, then simply choose to bind that to the OkButtonEnabled in our Login class:

    image 

    Press OK to save your changes.

    Initialize the binding in the form’s constructor

    The final step in the binding process is to perform some initalization on the login form, so that we have an actual object to store the values for username and password in. This can be passed to the form as a constructor argument, a property, or method, or be a built-in object. For the sake of this blog entry, I’ll simply use it as a publicly available property. Choose your login-form, switch to code view, and set the following lines of code:

    public partial class frmLogin : Form
    {
        // Our notification object:
        private Login _loginObject;

        public frmLogin( )
        {
            InitializeComponent( );

            _loginObject = new Login( );

            // Associate the databind with our notificationObject
            loginBindingSource.Add( _loginObject );
        }
    }

     

    That’s it.

    When you run your application, you will see that the OK button does not enable itself before username and password have values. What you may find odd, is that you have to change focus from one textbox to another in order to see this. This is because the value from the textbox is only passed to the object when it loses focus. If you want a quicker, more live update, you can, for example, choose to update the object on the KeyUp event, as an example.

    Summary

    Databinding forms to class objects is simply a matter of implementing the INotifyPropertyChanged interface. You can only databind properties, but with a little fantasy, the possibilities are many.

    You also have the added benefit of being able to unit-test ALL of the behavior that goes on in your dialog without requiring manual intervenion.

    As a result, you can take presentation behavior classes with you from a windows forms project to a WPF or SilverLight project with very little effort, both tests and behavior are already coded, all you have to do is to bind that class to a different GUI. Rumor has it that Microsoft may do something to bring INotifyPropertyChanged funcionality to the asp.net platform aswell, but at the time of writing this blog entry, this is not supported.

    Sample project can be downloaded here

    Within the context of testing

    This post  is written for .Net, using C#, but the methods in use should be fairly easy to implement in most other computer languages.

     

    Background

    I’ve often looked for a good way to write reusable testing scenarios that were clean to use, easy to set up and most importantly – easy to read six months afterwards.

    Looking at one of Ayende’s blog posts, where he discusses  scenario driven tests, I found something lacking: Whilst he has a great thing going for testing scenarios against a set context, he has limited himself to a very constrained situation, something that I needed to expand to suit my needs. The issue is that having a context that represents “the system” is not enough – I want to be able to specify exactly the state that my system is in when I execute a scenario, with the ambition of being able to re-use the various situations.

     

    Situations and Settings

    I wanted to be able to change contexts with ease, so that my test scenarios ultimately look something like:

    [TestClass]
    public class EventMonitorTests : TestBase
    {
        [TestMethod]
        public void Given_When_Then( )
        {
            using( DdTestContext testContext = new DdTestContext( true ) )
            {
                // Prepare
                int initialCount = testContext.Clients.TotalResponseCount( );
                PrepareSituation< RegisterThreeClients >( testContext );
    
                // Invoke                
                ExecuteScenario< RespondToAllClients >( testContext );
    
                int actualCount = testContext.Clients.TotalResponseCount( );
    
                // Assert
                actualCount.ShouldBeExactly( initialCount + 3 );
            }
        }
    }

     

    The idea is to introduce an interface ISituation as well as IScenario that are known to my test base-class. I can then invoke a Situation and Scenario in various combinations, so that I can test behaviors under different circumstances without having to repeat myself.

    ISituation has a Prepare statement, while an IAction  has an Execute method, both accepting the testContext object:

    public interface ISituation
    {
        void Prepare( DdTestContext testContext );
    }
    
    public interface IScenario
    {
        void Execute( DdTestContext context );
    }

    I gave it some thought as to whether I needed this separation or not, but concluded that having a clean separation between rigging a situation and executing a scenario better helps the reader to understand the tests.

    Additionally, I needed to declare the methods within the base class that are responsible for executing PrepareSituation and ExecuteScenario:

    public void PrepareSituation< T >( DdTestContext testContext ) where T : ISituation, new( )
    {
        T situation = new T( );
        situation.Prepare( testContext );
    }
    
    public void PrepareScenario< T >( DdTestContext testContext ) where T : IScenario, new( )
    {
        T scenario = new T( );
        scenario.Execute( testContext );
    }

    The functions are limited to accepting only objects that honor the respective interfaces.

    This takes care of the execution, as you can guess,For the sake of being practical, whenever I am writing a new batch of scenarios that I would like to test, I often end up writing most ISituation implementations within one single Situations.cs file as well as gathering the IScenario implementations in a corresponding Scenarios.cs file. This is purely to keep the aspects together, when they are simple.

     

    image

    This depends largely on the complexity of the situations and scenarios. For rigging up more complex scenarios, I would normally use a sub-folder within my solition explorer, and name each file after it’s class name, as is normal.

     

    The Context class

    Initially, I wanted a nice, controlled way to control transactions for my tests, as they often interact with database. The class DdTestContext represents the system under test as a whole, and can thus contain some sort of transaction object that is configured for the database being tested.

     

    public class DdTestContext : IDisposable
    {
        private Transaction _transaction;
    
        public DdTestContext( bool useTransaction )
        {
            if( useTransaction )
            {
                _transaction = new Transaction( );
                _transaction.Begin( );
            }
        }
    
        public void Dispose( )
        {
            if( _transaction == null )
                _transaction.Rollback();
        }
    }

    Thus, with this construct, I now have a somewhat stable way of executing my tests within a transactional context without too much effort:

    [TestMethod]
    public void Given_When_Then( )
    {
        using( DdTestContext testContext = new DdTestContext( true ) )
        {
            // Prepare
    
            // Invoke
    
            // Assert
            Assert.Inconclusive( "Not yet implemented" );
        }
    }

    This instantly became a code snippet :)

    Every test that executes within the using clause will initiate a transaction, and roll it back again once the scope is out (or unhandled exceptions occur). My database is safe, for now.

    Whenever I don’t need database support (Unit tests), I can simply opt for false as the constructor argument and no transaction will be initiated for that particular context.

    I dragged the using  statement into each test as opposed to initializing the testcontext in a pre/post method in order to control the use of transactions individually for each test.

     

    Still to come

    • How I expanded the testcontext with useful functions
    • Using extension methods extensively

    Comments are very welcome :)