Thursday, 13 December 2012

Capturing console output with Delphi 2010/XE (revised)

Following my previous post (Capturing console output with Delphi 2010/XE) and with all the great comments received on it, I have decided to publish the new solution provided by Lübbe Onken which solves the hanging issue when capturing the output for different kind of commands like ping, netstat, etc. The problem occurs on the last ReadFile which this solution will fix.
Here I'm summarizing Lübbe Onken comments on this issue:
"The current implementation assumes that if the external process is not finished yet, there must be something available to be read from the read pipe. This is not necessarily the case. If we use PeekNamedPipe to check for available data before entering the internal repeat loop, everything is fine.
I also put the CloseHandle into try ... finally and moved Application.ProcessMessages behind the internal read loop, because IMHO the screen update is better handled after processing the callback than before. But this is just cosmetic."

Here you can find the source code:


usage:

I want to say thanks to everyone who spend time looking at this issue and for making the community work and grow.
Jordi

Monday, 6 August 2012

Rpi and GPIO testing

In this article I'm showing my progress with the RPi using the GPIO. There are lots of interesting articles where people is doing the same, but you won't get the same feeling that I have until you test it by yourself. This application processor board is extremely delicate and you need the get used to its I/O, typical voltage values (3.3V), maximum current (8-11mA), etc. Few basic things that will help you not to burn the RPi (connect resistors after every LED, etc). My example is quite simple but with academical purposes and I'm sure it will inspire others. I'm using the slice of a pi extension board where you can easily get the connectors for GP0-GP7 outputs and lit some LED's programmatically.

Material (apart from your RPi):


First thing is to correctly identify the GP Inputs/Outputs from the Slice of Pi (GP0 to GP7 pins). Here are my findings and the correct pin numeration:
GPIO     Slice of Pi
Pin 11   GP0
Pin 12   GP1
Pin 13   GP2
Pin 15   GP3
Pin 16   GP4
Pin 18   GP5
Pin 22   GP6
Pin 07   GP7

As you can see, they are not in order, so you need to spend time looking for the right pins. I still need to identify all the other pins but I'll get to it.

The following code is just lighting up 8 LED's using 8 GPIO pins as outputs. Each pin is connected to a 220 ohm resistance plus a red LED and all terminations to GND.

Source code:


Example with two LED's:

Here is the video displaying the results:


Keep playing!.

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.