Little experiments

I try, I share.

Golo - Little 5

Ok! That’s time to sync everyone on the state of GoloHttpServer.
First of all, I created a GitHub for this and you’re more than welcome to contribute, ask questions or even just talk about it.

This will allow you to take a look at the implementation of the run function which handle the Http request and response.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function run = |connectedClient, serverState| {       

  let inFromClient = BufferedReader( InputStreamReader (connectedClient:getInputStream()))
  let outToClient = DataOutputStream(connectedClient:getOutputStream())

  let requestString = inFromClient:readLine()
  let headerLine = requestString

  let tokenizer = StringTokenizer(headerLine)
  let httpMethod = tokenizer:nextToken()
  let httpQueryString = tokenizer:nextToken()
  let responseBuffer = StringBuffer()
  responseBuffer:append("<b> This is the HTTP Server Home Page.... </b><BR>")
    responseBuffer:append("The HTTP Client request is ....<BR>")

    while (inFromClient:ready()) {
        # Read the HTTP complete HTTP Query
        responseBuffer:append(requestString + "<BR>")
      requestString = inFromClient:readLine()
  }

  httpMethodHandle(httpMethod, httpQueryString, responseBuffer, outToClient)
}

As you can see, I lied a bit: the run function is just here to prepare all the needed element to delegate to httpMethodHandle.
The input and output buffers are initialized, the query is tokenized and everything is set to httpMethodHandle function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function httpMethodHandle = |methodName, queryString, responseBuffer, outToClient| {
  case {
      when methodName == "GET" {
          var fileName = queryString:replaceFirst("/", "")
          if (queryString=="/") {
              # The default home page
              fileName = Parameters(): HOME()   
          }
          fileName = URLDecoder.decode(fileName)
          if ( File(fileName):isFile()){                              
              sendResponse(200, fileName, true, outToClient)
          } else {
              sendResponse(404, "<b>The Requested resource not found ...." + "Usage: http://127.0.0.1:5000 or http://127.0.0.1:5000/<fileName></b>", false, outToClient)
          }    
      }
      otherwise {
          sendResponse(404, "<b>The Requested resource not found ...." + "Usage: http://127.0.0.1:5000 or http://127.0.0.1:5000/<fileName></b>", false, outToClient)
          }
      }
}

This method has a simple goal: analyze the resource name asked and return the appropriate content.
Note the use of case..when..otherwise Golo statements.
This is quite useful isn’t it ?

From here, I’ll try to use GoloHttpServer for side projects.
For example, during MixIT 2013, I attended a conference on the Dart language.
Serve HTML pages and javascripts ? That may be doable with GoloHttpServer ;)

As usual, I’m waiting your emails and comments.
Don’t be shy and drop me an email as the other little hackers that prefers that to public comment! As of today, everyone had my answers ;)

Why? Oh Why?

For 2 days, it’s MixIT 2013 days!
This conference has a lot of qualities, but for me, it’s THE event that helped me surviving previous years.

This may sound a bit too much, but believe me: I was and still am a true geek!
I like technology, I like computers, I like science… and I like to share!
But when you work in a company that prevent you from any innovation, where every technical act is surrounded by political thoughts, you’re stucked.
Being stucked in your brain is not a very pleasant situation…

Going to MixIT was a break in those sad moments, this place was full of people with knowledge and the will to share.
There were hard moments when people were laughing on old technologies and working methods: this was my daily tools and environment!
But this was the opportunity to meet and exchange ideas with passionnate peoples.
After the first MixIT, I stopped trying to push Groovy in the product I was working on: instead, I just had to do it :)
After the second year, I decided to look for a new job: I found one in the month after!

Yes, MixIT is brighter, stronger and clean your clothes better! ;)

This year is even better: I love my job, I love my company and I even use some of technologies shown here as innovatives ;)

So, thanks MixIT, thanks all the people behind this event!
Long live to MixIT!

PiG 2 - First Interaction

In my previous article I explained some steps useful for my Little Experiment with my Raspy.
Yes, I gave it a name, I’m stupid and geek ;)

This time I’ll explain my first usage of Golo to control the GPIO of my Raspy.
If you didn’t prepared your Raspy for Golo usage, just follow my article.
All those previous articles looks like I prepared something ? ;)

When you have the hardware and software ready, we can jump on the next step: light a LED! ;)

First, connect the cobbler breakout to the Raspy and the breadboard.
It will allow multiple future experiments without more soldering.

The long board Board and cable

Prepare a LED. I choosed a red one, some K2000 reminiscence ;)
The resistor is here to limit the current allowed through the LED.
If you want further explanation on this, you can read Gordons projects page or the Pi4J corresponding page.
hardware for first project close view of LED and resistor

Start by pinning an orange cable to pin marked #18. It is the GPIO1 pin.
Use then a green cable to pin the GND pin.
Orange on pin #18, Green on GND

Put a resistor and then a LED:
put the resistor and the LED

Don’t forget to close the circuit:
close the circuit

From now, you have everything to run the first sample from the Pi4J project.
First, follow their instructions to download and setup the library
Check that the control sample in Java is working.

If you saw the LED switching on and off, you’re just one step ahead of this article goal.
You have the hardware, you have the Java sofware.

But wait… where’s the Golo software ? :)

Oh, look! Here!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
module PiG.gpio.control

# adapted from http:#pi4j.com/example/control.html
# which is
# Copyright (C) 2012 - 2013 Pi4J
# Licensed under the Apache License, Version 2.0 (the "License")
#
# Golo version by Thierry Chantier
# Copyright (C) 2013 Pi4J
# Licensed under the Apache License, Version 2.0 (the "License")

import com.pi4j.io.gpio.GpioController
import com.pi4j.io.gpio.GpioFactory
import com.pi4j.io.gpio.GpioPinDigitalOutput
import com.pi4j.io.gpio.PinState
import com.pi4j.io.gpio.RaspiPin

import java.lang.Thread

#
# This example code demonstrates how to perform simple state
# control of a GPIO pin on the Raspberry Pi.
#
# @author Robert Savage (original java version)
# @author Thierry Chantier (Golo-lang version)
#

function main = |args| {

        println("<--Pi4J--> GPIO Control Example ... started.")

        # create gpio controller
        let gpioInstance = GpioFactory.getInstance()

        # provision gpio pin #01 as an output pin and turn on
        let pin = gpioInstance: provisionDigitalOutputPin(RaspiPin.GPIO_01(), "MyLED", PinState.HIGH())
        println("--> GPIO state should be: ON")

        Thread.sleep(15000_L)

        # turn off gpio pin #01
        pin: low()
        println("--> GPIO state should be: OFF")

        Thread.sleep(1000_L)

        # toggle the current state of gpio pin #01 (should turn on)
        pin: toggle()
        println("--> GPIO state should be: ON")

        Thread.sleep(15000_L)

        # toggle the current state of gpio pin #01  (should turn off)
        pin: toggle()
        println("--> GPIO state should be: OFF")

        Thread.sleep(5000_L)

        # turn on gpio pin #01 for 1 second and then off
        println("--> GPIO state should be: ON for only 1 second")
        # set second argument to 'true' use a blocking call
        let duration = 1000_L
        pin: pulse(duration: longValue(), true)

        # stop all GPIO activity/threads by shutting down the GPIO controller
        # (this method will forcefully shutdown all GPIO monitoring threads and scheduled tasks)
        gpioInstance: shutdown()
}

My project is now going well. I’m starting to convert to Golo every sample from Pi4J and give them back as a contribution.
I hoped to have enough time to show a full video of all the process, but it was quicker to do this article.

If you have any question, feel free to comment or to drop me an email.

PiG 1 - Soldering Iron Step

so what ? You started the GoloHttpServer, showed something on Raspberry and… nothing ?
Yeah, I know. But c’mon, I still need some sleep and still don’t have 72h days ;)

Last week end, I started the next step in the Little Hardware meets Little Software. yep, I bring back on the desk my soldering iron!

I had to prepare several items:

So everything is in place.
Everything ready!

Let’s start by puting the header pins in the cobbler PCB.
cobbler PCB and header pins

To have something stable, you can use a small breadboard and slot the header pin in it.
use a breadboard to stabilize during soldering use a breadboard to stabilize during soldering

I didn’t work with a soldering iron for several years… not too bad :)
not that bad after all those years without soldering ;)

Don’t forget the ribbon cable socket:
ribbon cable socket

At that point, the cobbler breakout is ready.
Now it’s time to put some wires on the HD44780.

The wire stripper is my best friend when there’s a lot of wire to prepare:
prepare your wires

A third hand tool is very helpful to solder the wire to the LCD panel.
use a third hand!

You have to wire pin 1 to 6, then 11 to 16:
1 to 6, then 11 to 16

The LCD has now wires. It could be better and I wonder if I won’t try to solder head pins on another LCD:
could be better

Here we go!
Here we go!

At the end, I have now everything to start to work with my Pi!
The next step has already started and I’m running basic piece of code to test the cobbler, the Gpio…
The Gpio and its wonderful pin numbering, guided by a logic that only an advanced Scala user may understand ;)

See you soon, with pieces of Golo lang to interact with a small red led on a board :)

Golo on the Raspberry

On the Little experiments desk, there are a lot of Little hardware.
I must admit I have some favorites among them, but don’t tell them ;)

One of them is an Android USB key, MK808B, which allows me to run Android any TV with a HDMI input.
Used with a bluetooth PlayStation keyboard, it’s pure fun.
Unfortunately, Android devices are running a modified JVM called Dalvik which has one major drawback: it’s based on code without invokeDynamic.

What does it mean ?
It means a awful thing: Golo won’t run on it!
I read some work from Jérôme Pilliet about implementing JSR 292 on Dalvik, but it’s a work in progress with no garantee.

So, let it go…
But wait, there’s a second device I really enjoy: my RaspBerry Pi!

In a previous experiment, I ran a Tomcat server on it, so at least Java is running.
And, better than a painful experiment, Golo website itself provides instructions on setting up a running Pi Golo :)
It was for me the opportunity to try also ArchLinux.

The only issue I had was that the root user is unable to log directly on the device: you must connect through SSH, which means knowing the IP address.

I add the modified bin/* files for those who wants them quickly.

Now let’s back to work and see if one of my recent dream may come true: use the Raspberry GPIO to control a HD44780U LCD with Golo.
I know… silly… and I have to publish follow up on the GoloHttpServer… I know ;)

Enjoy your PI Golo!

Golo - Little 4

So, last time I told you I started to write some kind of GoloHttpServer.
In that process (which is still WIP) I had several questions.

One of the first was: a server will receive several requests, I need to launch threads.
I knew how to do that with Java, how to do that with Golo.

The solution I found is based on the below code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
module little.experiment4_1

import java.lang

function run = |number| {
  println ("I am thread "+number)
}

function main = |args| {

  for (var thread_number = 0, thread_number < 4, thread_number = thread_number + 1) {
      let process = java.lang.Thread({run(thread_number)}: to(Runnable.class))
      process: start()
  }
}

That’s nice and I’m sure some of you know how to do it in different ways.
I will enjoy suggestions and comments on this.

But remember, I’m explaining how to build a http server.
Having some threading methods is useful, but we need to receive something from a browser.
Let’s start some game with sockets !

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
module little.experiment4_2

import java.net.InetAddress
import java.net
import java.lang

function run = |connectedClient| {   
  println ("step after step young padawan. Http answer will be in next article ;)")
}

function main = |args| {
  # create a socket
  let addr = InetAddress.getByName("127.0.0.1")
  let Server = ServerSocket (5000, 10, addr)
  println ("TCPServer Waiting for client on port 5000")

  # just loop until a request, then quit
  # this is for sample purpose of course ;)
  var serverRun = true
  while(serverRun) {
      # get the request
      let clientSocket = Server: accept()
      # launch the process of this request
      let process = java.lang.Thread({run(clientSocket)}: to(Runnable.class))
      process: start()
      # for this sample, just tell we want to stop
      serverRun = false
  }
}

I hope everything is clear with the included comments.
If you have questions, use comments here or send me a note to my email if you prefer.

Golo - Little 3

Ok folks ! First, I hope you didn’t missed the release of Golo.

I hoped to publish some article on the D-day but my daughter had an unplanned trip to hospital.
She’s fine now, I spent some time watching her sleeping.

So, this won’t be a huge post but still hope to introduce you to the coming plans.

What I really like with new languages is that everything has to be discovered.
It is often a moment where you can both use fresh eyes on your way of coding and learn a lot on various topics. Come on, you know what kind of topics…
Those you already should have digg into.
Use this new language as a good reason !

Everyone will choose his own topics.
Philippe Charrière started to digg what Play! framework looks like behind the scene and decided to write his own vision with Golo. (if you don’t understand french, ask him some translation ;) )

But in my case, I first choose to see the internals of a Http server.
Yes, a simple Http server. Something like com.sun.net.httpserver
I will post here the step of what I had to try.

In the meantime, if you already jumped on Golo board, you can have a look to n’Golo aka nano.Golo.
This place will be a sharing space for all Golo users, newbie, seasoned, curious, my mom… ;)
See you soon…

Golo - Little 2

The D-day is coming for Golo and be sure to attend Julien’s talk at Devoxx !

In the meantime, here is a new piece of Golo.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
module little.experiment2_1

import java.lang

function functionWithCase = |inputParameter| {
  case {
      when inputParameter == "This value" { println("this value spotted") }
      otherwise { println("otherwise was the answer") }
  }
}

function main = |args| {
  functionWithCase("This value")
  functionWithCase("not something to handle")
}

This illustrate the use of the Golo case word.
As you can see, the case expression is quite simple:
each when is based on a conditionnal expression that will allow the specified code to be executed.

It’s that simple !

But simple doesn’t mean powerless !
Golo allows you to write when conditions with several variables that may have different possible types.
Just look below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
module little.experiment2_2

import java.lang

function otherValue = { println("This value was numeric") }

function functionWithCase = |inputParameter, secondParameter| {
  case {
      when inputParameter == "This value" { println("this value spotted") }
      when secondParameter == "second" { println("second value") }
      when inputParameter == 42 { otherValue() }
      when (inputParameter == "first") and (secondParameter == "second too") { println("both") }
      otherwise { println("otherwise was the answer") }
  }
}

function main = |args| {
  functionWithCase("This value", "second")
  functionWithCase(42, "second")
  functionWithCase("not something to handle", "")
  functionWithCase("first", "second too")
}

That’s it for today folks !
Of course, feel free to contact me and ask question questions.
All comments are welcome here too.

See you when Golo is out ;)

Golo - Little 1

I think it’s time to start some Golo experiment.

Of course, everyone wanted the mandatory HelloWorld.
But hey, that’s a blog called “Little Experiment” ;)

Ok, ok, the HelloWorld is available at Golo website, and as a present to my fellow readers, here is a copy here ;)

1
2
3
4
5
module hello.World

function main = |args| {
  println("Hello world!")
}

Save this to a helloworld.golo file.
To be sure, if your Golo environment is properly setup, all you have to do is:

1
2
> gologolo helloworld.golo
Hello world!

The interesting Golo things here are:

  • the Golo code is placed in a module (names separated with dots)
  • you can execute a Golo module if there’s a main function
  • you see how to define a function
  • gologolo is the tool that compile then execute your code. You can use goloc to compile and later golo to run it.

But you know what ?
If you have a ticket to Devoxx, don’t miss julien’s talk there !

Google Plus Added to the Blog

This evening, I just had time to setup a second machine to be able to blog from my iMac at home.
It went quite quickly, a matter of some brew commands and a bit of Heroku magic.

The blog is now cloned both at home and at work, it will ease things.

As I wanted a little more today, I added the google Plus button on posts and on the main page.

All I needed to do was modifying the _config.yml file.

1
2
3
# Google +1
google_plus_one: true
google_plus_one_size: medium

I have now to figure out what to publish first about Golo.

Maybe you have an opinion on this ?
Comments are more than welcome.