Sunday, 29 July 2012

Raspberry Pi...the basics

After playing for a day with my Raspberry Pi, here I'm compiling a list of tools that would help you setting RPi up correctly. As I'm testing everything under Python and I want to control it using my laptop (Windows 7), I need different ways to be more productive and faster when developing on it. In my case, I'll need a Python editor like geany, GPIO library and remote desktop using Xming and PuTTY via SSH. As stated in my previous post I'll build a small robot using the following mechanical and electronic parts (All of them bought from HobbyTronics) expending less than £50:
Update the system first:
root@raspberrypi:~# apt-get update
Installing Geany:
root@raspberrypi:~# apt-get install python geany xterm
Downloading GPIO RPi Python from Google code:
root@raspberrypi:~# wget https://raspberry-gpio-python.googlecode.com/files/python-rpi.gpio_0.3.1a-1_armhf.deb
--2012-07-29 10:20:19--
https://raspberry-gpio-python.googlecode.com/files/python-rpi.gpio_0.3.1a-1_armhf.deb
Resolving raspberry-gpio-python.googlecode.com
(raspberry-gpio-python.googlecode.com)... 173.194.66.82,
2a00:1450:400b:c00::52
Connecting to raspberry-gpio-python.googlecode.com
(raspberry-gpio-python.googlecode.com)|173.194.66.82|:443...
connected.
HTTP request sent, awaiting response... 200 OK
Length: 10824 (11K) [application/x-debian-package]
Saving to: `python-rpi.gpio_0.3.1a-1_armhf.deb'

100%[======================================] 10,824      --.-K/s   in 0.1s

2012-07-29 10:20:27 (71.2 KB/s) - `python-rpi.gpio_0.3.1a-1_armhf.deb'
saved [10824/10824]
Installing the package GPIO RPi:
root@raspberrypi:~# sudo dpkg -i
python-rpi.gpio_0.3.1a-1_armhf.debSelecting previously unselected
package python-rpi.gpio.
(Reading database ... 54876 files and directories currently installed.)
Unpacking python-rpi.gpio (from python-rpi.gpio_0.3.1a-1_armhf.deb) ...
Setting up python-rpi.gpio (0.3.1a-1) ...
Testing the GPIO Rpi library:
Just open Geany and paste the following source code:

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)

GPIO.setup(11, GPIO.IN)
GPIO.setup(12, GPIO.OUT)

#set up output 12 as true.

GPIO.output(12, GPIO.HIGH)

while True:
        time.sleep(1)
        input_11 = GPIO.input(11)
        print "%s %r" % ("Input 11 value is", input_11)
        time.sleep(1)

Compile it and run it. It should display the value of Pin 11. If you can change the state of that input, the display will show the change.

Starting up the SSH server:
root@raspberrypi:~# service ssh start

Download PuTTY and Xming and install them:
Once installed, run PuTTY and under Session options, use the IP of the RPi. (to get the IP just run the ifconfig command):

And enable the option X11 forwarding under connection options:

Once done, open the connection and use your credential to login (by default user: pi password: raspberry).

As soon as you are in, type startlxde and Xming will take over and it will display the RPi desktop on your local machine.


Check out the parameters for Xming as the short-cut should call: "...Xming.exe" -clipboard -rootless.

Related links:

Taking a bite of my Raspberry Pi!

Lots of thinks are going on, new interesting projects, new ideas but no time to post. I've just got my new Raspberry Pi and I'm planning to build a small robot with it using the GPIO. I'll use all the tools available from the internet and I'll see if I can write something using Pascal/Delphi and share it with the community (I've seen GPIO libraries for C# and Java). I'm really excited about it because it opens a set of possibilities, not only for Developers but also for students who will be hooked on to this beautiful board. In this post and the following ones you'll find my progress with my RPi and all the source code. I'm still building up the idea and I'm waiting for different parts of the robot to arrive. At least I've got the Raspberry Pi model B board, the keyboard, HDMI cable, an SD with Raspbian "weezy" distribution OS and loads of patience. 


Quick steps (Instructions working under Windows OS):

1. Download Raspbian.
2. Download Image writer for windows (to burn the OS into the SD Card).
3. Once installed, plug all necessary things to the board and turn it on!.
4. Configure the different options (SSH Server, Keyboard layout, Date&Time, etc)
5. run startx command and off you go!.


Running my "Hello world" using python:


Now I need to tinker with GPIO and get used to it. I'll use the GPIO.RPi python module to control the Input/Output signals.

Stay tuned for my forthcoming articles!.

Related links:

Saturday, 2 June 2012

Mocking methods

I have been using Mock objects a lot with Delphi and I have implemented a small example and that you can find available in my personal repository on Google code. This simple example plays with the signature of the methods and uses delegates to return what we want to return. There are lots of ways to mock objects and lots of really good available frameworks: PascalMock, Ultra Basic MockObjects, DelphiMocks, etc. but sometimes we just want to mock some of the methods reintroducing a new signature. This simple example has helped me a lot in my unit testing and I hope you find it enough interesting to use it.


Basically we need an Interface to Mock which will contain all the contracts of the instance. TMock will be mocking the Interface and we need to set up the methods on the mockable class in a particular way using delegates. With this method TMock will be able to inject a new delegate and use it in our unit testing.

The declaration of TMock is quite neat:

type
  IMock = interface
  end;

  TMock<T> = class(TInterfacedObject,IMock)
  private
    FMockClass : T;
  public
    function SetUp() : T;
    constructor Create(mockingClass : T);
  end;

{ TMock<T> }

constructor TMock<T>.Create(mockingClass: T);
begin
  FMockClass := mockingClass;
end;

function TMock<T>.SetUp(): T;
begin
  Result :=  FMockClass;
end;
Then the IServer interface will have two methods which I want to mock. The delegates on the IServer will have to be extended as a property to then be able to overwrite them during the unit testing.

  //Contract definition to be Mocked.
  IServer<T, TResult> = Interface
    //Send structure
    function GetSendMessage() : TFuncParam<T, TResult>;
    procedure SetSendMessage(const Value: TFuncParam<T, TResult>);
    property SendMessage : TFuncParam<T, TResult> read GetSendMessage write SetSendMessage;
    //Receive structure
    function GetReceiveMessage() : TFunc<T>;
    procedure SetReceiveMessage(const Value: TFunc<T>);
    property ReceiveMessage : TFunc<T> read GetReceiveMessage write SetReceiveMessage;
  End;

It is really important to define the visibility of the methods on the implementation side so the mock only sees the methods we really want to redefine.

Then when the mock test is defined, it will only display the methods available to inject:
To set up the test, we only need to use the following declaration:

procedure TestTProtocolServer.TestCommunicateWithMock;
var
  ReturnValue: Boolean;
  Server: IServer<String, Boolean>;
  mock : TMock<IServer<String, Boolean>>;
begin
  Server := TServer.Create;

  mock := TMock<IServer<String, Boolean>>.Create(Server);

  //Set up the mocking methods using delegates:
  mock.SetUp().SendMessage := (function (message : string) : boolean
  begin
    result := True; //Return always true whatever the message is
  end);

  mock.SetUp().ReceiveMessage := (function () : string
  begin
    //Return the same message the server would reply
    result := 'This is the message from the server!';
  end);

  FProtocolServer := TProtocolServer.Create(mock.SetUp());
  try
    ReturnValue := FProtocolServer.Communicate;
    CheckTrue(ReturnValue, 'Communication with the Server Failed');
  finally
    Server := nil;
    mock.Free;
    FProtocolServer.Free;
    FProtocolServer := nil;
  end;
end;

With this simple method we can reuse existing code and just rewrite what we need to mock as the method we are calling depends on other objects/libraries, etc which are not testable. Note that this is not a framework, it is just a simple example where I need to mock a method and I don't want to use any of the existing frameworks. I like the way moq works and I wanted something similar (I wish we had lambda expressions, maybe one day!):

var mock = new Mock<ITest>();

mock.Setup(p => p.SendMessage(Is.Any<String>))
    .Returns(true)

It has loads of drawbacks as you will need to change the signature of your methods using delegates and sometimes it is not easy to do it, but I have been using it and it does the job.

Please, have a look at the repository and do not hesitate to leave any comment.

Thursday, 31 May 2012

Project Updates

It is time for a retrospective now that we have gone through the first half of the year. Projects are coming along and I will be updating  TDPE (Thundax Delphi Physics Engine)  and  PZaggy (Graph tool)  which will have the source code available by the end of the year. I have been working on side projects like ATOM Monitor to keep track of your atom leaks (and yes, Delphi has atom leaks) and my personal repositories where you will find Delphi code snippets and small utilities I have been developing throughout the years and you will be able to download them and use them for free. This is the way to make Delphi community grow and improve the way we develop Delphi apps using the power of the language using: fluent interfaces, delegates, mock objects, Unit tests, etc.

I will be redesigning as well, the entire website to make it more functional with an emphasis on Open Source projects and other really interesting stuff.

So, stay tuned and I look forward to your comments!.
Jordi

Thursday, 5 April 2012

DUnit and TCustomAttributes

In this article I am playing with Unit tests and TCustomAttributes as I am working on different ideas to build up a lightweight testing framework.  Basically I liked the idea of TestCase attribute from NUnit and I wanted to do something similar using TCustomAttributes and accessing those attributes using the Delphi RTTI library. To understand better my purposes have a look at the following example extracted from NUnit webpage:

[TestCase(12,3,4)]
[TestCase(12,2,6)]
[TestCase(12,4,3)]
public void DivideTest(int n, int d, int q)
{
  Assert.AreEqual( q, n / d );
}

This simple example will execute three times the method or test using the parameters defined on the test case attributes. What if we could perform something similar? Would not be cool?

Here is what I have done so far:


Creation of the Custom Attributes:
type
  TUserPasswordAttribute = class(TCustomAttribute)
  private
    FPassword: string;
    FUserName: string;
    Fresponse: Boolean;
    procedure SetPassword(const Value: string);
    procedure SetUserName(const Value: string);
    procedure Setresponse(const Value: Boolean);
  public
    constructor Create(aUserName: string; aPassword: string; aResponse : Boolean);
    property UserName: string read FUserName write SetUserName;
    property Password: string read FPassword write SetPassword;
    property response : Boolean read Fresponse write Setresponse;
  end;

  TUserAgeAttribute = class(TCustomAttribute)
  private
    FAge: integer;
    FUserName: String;
    Fresponse: Boolean;
    procedure SetAge(const Value: integer);
    procedure SetUserName(const Value: String);
    procedure Setresponse(const Value: Boolean);
  public
    property UserName : String read FUserName write SetUserName;
    property Age : integer read FAge write SetAge;
    property response : Boolean read Fresponse write Setresponse;
    constructor Create(aUserName : string; aAge : Integer; aResponse : Boolean);
  end;

{ TUserPasswordAttribute }

constructor TUserPasswordAttribute.Create(aUserName, aPassword: string; aResponse : Boolean);
begin
  SetUserName(aUserName);
  SetPassword(aPassword);
  Setresponse(aResponse);
end;

procedure TUserPasswordAttribute.SetPassword(const Value: string);
begin
  FPassword := Value;
end;

procedure TUserPasswordAttribute.Setresponse(const Value: Boolean);
begin
  Fresponse := Value;
end;

procedure TUserPasswordAttribute.SetUserName(const Value: string);
begin
  FUserName := Value;
end;

{ TUserAgeAttribute }

constructor TUserAgeAttribute.Create(aUserName: string; aAge: Integer; aResponse : Boolean);
begin
  SetUserName(aUserName);
  SetAge(aAge);
  Setresponse(aResponse);
end;

procedure TUserAgeAttribute.SetAge(const Value: integer);
begin
  FAge := Value;
end;

procedure TUserAgeAttribute.Setresponse(const Value: Boolean);
begin
  Fresponse := Value;
end;

procedure TUserAgeAttribute.SetUserName(const Value: String);
begin
  FUserName := Value;
end;

Those two custom attributes will serve as an example for what I intend to do. I need to test a login and some data from a current user and those bespoke attributes would be used by the test case.

The Framework:
type
  TAttributeProc = reference to procedure(CustomAttr: TCustomAttribute);

  TFrameworkTestCase = class(TTestCase)
  public
    procedure TestAttributesMethod(CustomProc: TAttributeProc);
  end;

implementation

{ TFrameworkTestCase }

procedure TFrameworkTestCase.TestAttributesMethod(CustomProc: TAttributeProc);
var
  ContextRtti: TRttiContext;
  RttiType: TRttiType;
  RttiMethod: TRttiMethod;
  CustomAttr: TCustomAttribute;
begin
  ContextRtti := TRttiContext.Create;
  try
    RttiType := ContextRtti.GetType(Self.ClassType);
    for RttiMethod in RttiType.GetMethods do
      for CustomAttr in RttiMethod.GetAttributes do
        CustomProc(CustomAttr);
  finally
    ContextRtti.Free;
  end;
end;

As you can see TFrameworkTestCase inherits from TTestCase and it adds the magic of reading the custom attributes and invoking the delegate as many times needed.

Using the small framework:
unit TestUnit1;
{

  Delphi DUnit Test Case
  ----------------------
  This unit contains a skeleton test case class generated by the Test Case Wizard.
  Modify the generated code to correctly setup and call the methods from the unit
  being tested.

}

interface

uses
  TestFramework, Windows, Forms, Dialogs, Controls, Classes, RTTI, SysUtils, Variants,
  Graphics, Messages, Unit1, StdCtrls;

type
  TestTLoginCase = class(TFrameworkTestCase)
  strict private
    FLogin: TLogin;
  public
    procedure SetUp; override;
    procedure TearDown; override;
  published
    [TUserPasswordAttribute('User1', 'Password1', True)]
    [TUserPasswordAttribute('User2', 'Password2', True)]
    [TUserPasswordAttribute('User3', 'Password3', True)]
    [TUserPasswordAttribute('User3', '', False)]
    procedure TestUserLogin;
    [TUserAgeAttribute('User1', 26, True)]
    [TUserAgeAttribute('User2', 27, True)]
    [TUserAgeAttribute('User3', 28, False)]
    procedure TestUserAge;
  end;

implementation

procedure TestTLoginCase.SetUp;
begin
  FLogin := TLogin.Create;
end;

procedure TestTLoginCase.TearDown;
begin
  FLogin.Free;
  FLogin := nil;
end;

procedure TestTLoginCase.TestUserAge;
var
  aAge: integer;
  aUserName: string;
  aResponse : boolean;
begin
  TestAttributesMethod(procedure (CustomAttr : TCustomAttribute)
    begin
        if CustomAttr is TUserAgeAttribute then
        begin
          aUserName := TUserAgeAttribute(CustomAttr).UserName;
          aAge := TUserAgeAttribute(CustomAttr).Age;
          aResponse := TUserAgeAttribute(CustomAttr).Response;
          Assert(aResponse=(FLogin.fetchDatauser(aUserName)=aAge), 'Incorrect value ' + aUserName);
        end;
    end);
end;

procedure TestTLoginCase.TestUserLogin;
var
  aPassword: string;
  aUserName: string;
  aResponse : boolean;
begin
  TestAttributesMethod(procedure (CustomAttr : TCustomAttribute)
    begin
        if CustomAttr is TUserPasswordAttribute then
        begin
          aUserName := TUserPasswordAttribute(CustomAttr).UserName;
          aPassword := TUserPasswordAttribute(CustomAttr).Password;
          aResponse := TUserPasswordAttribute(CustomAttr).Response;
          Assert(FLogin.UserLogin(aUserName, aPassword)=aResponse, 'Incorrect user ' + aUserName);
        end;
    end);
end;

initialization
RegisterTest(TestTLoginCase.Suite);

end.

Notice that every test case contains a set of Custom attributes and they will be executed by using a delegate. I have included the Result parameter in the attribute so the test can know the result straight away and inform about it. 


Related links: