mar
09
2010

Welcome back NGW100!

A some time ago I’ve bricked my NGW100 board by overwritten the U-boot from flash. To fix it was necessary using a JTAG interface, so I check some alternatives.

Considering that NGW100 itself costs about US$ 89.00 could be more cheaper get another board than buying a JTAG device. Note that I looking for way to allow a programming Interface to flash and not other features available in a JTAG like source level debugging.

The bootloader for the NGW is stored in the parallell flash

Searching for a inexpensive solution I found this AVR Freaks thread teaching how to use cable wiggler or byteblaster to flash NGW.  Everyone that used Altera FPGA at least one time know about Byteblaster cable, was easy found one at university and try (thanks Prof. Robson Moreno)

I’m using Byteblaser I

I’ve compiled a new u-boot binary from BSP code and used a too called avr32prog (it’s windows-only) to record.

avr32prog.exe -c byteblaster -p LPT1 -f u-boot.img prog

The process is extremely slow, about 35 minutes to flash a 100kbyte binary (~ 50bps)

I have not had success the first time due some kind of “writing error”. I noted that if I use the computer (i.e.: browsing) when avr32prog is running the error happens faster, so I started the program a let flash the board “alone”. After finished just turn off the board, unplug JTAG connector and turn on the board again. It’s nice to see serial working again :-)

U-Boot 1.1.4-at0 (Mar 9 2010 – 01:55:04)

U-Boot code: 00000000 -> 000149cf data: 24000000 -> 24002d80
SDRAM: 32 MB at address 0×10000000
Testing SDRAM…OK
malloc: Using memory from 0×11fc0000 to 0×12000000
Flash: 8 MB at address 0×00000000
DRAM Configuration:
Bank #0: 10000000 32 MB

In: serial
Out: serial
Err: serial

Net: macb0, macb1
Press SPACE to abort autoboot in 1 seconds
Uboot>

mar
06
2010

SHOUTcast search

I’m working on a project using SHOUTCast. In order to know about services requests, especially XML output, I made this small program to display search queries.  The program perform an Http request and parse the result in a appropriate view.

screenshot

This code is hosted in Github.

$ git clone git://github.com/maluta/shoutcast-search.git
$ cd shoutcast-search
$ qmake && make && ./shoutcast-search

To listen some radio I cut & paste ‘Playlist’ info and put in some player. For example, to listen the Bob Dylan radio selected in screenshot I would do:

curl -s http://yp.shoutcast.com/sbin/tunein-station.pls?id=486

[playlist]
numberofentries=2
File1=http://68.90.68.227:8001
Title1=(#1 – 11/55) DylanRadio.com
Length1=-1
File2=http://66.55.139.212:7190
Title2=(#2 – 30/50) DylanRadio.com
Length2=-1
Version=2

As you can see, ouput has two URLs, so I select one and choose mplayer to play.

mplayer http://68.90.68.227:8001

Enjoy :-)

Bonus: A not beautiful way to play from command line…

curl -s http://... | egrep "^File1" | cut -c7- | xargs mplayer
fev
28
2010

Simple C macro for debugging

A little trick if you use printf to debug information in your code and don’t like to comment/uncomment.

#include <stdio.h>
 
#define dprintf if (debug) printf
 
const char debug = 1; /* or 0 if you want disable debug */ 
 
int main(int argc, char *argv[] ) {
     dprintf ("debug message");
     return 0;
}

Remember that using printf is just one way to debug your code and an excess can impair the efficiency to analyze the situation or catch bugs. If you need start your program, specifying anything that might affect its behavior; make your program stop on specified conditions; examine what has happened, when your program has stopped or change things in your program, so you can experiment with correcting the effects of one bug and go on to learn about another; use programs such as GDB or Valgrind (especially to memory management issues)

fev
24
2010

ipconfig over usb ethernet

I guess this post apply only if you are using Linux v.2.6.33-rc3 or above.

You would have noted that kernel IP auto-configuration is not usable for some USB-Ethenet dongles on newer kernel because it starts before the USB devices are found. This was already discussed on LKML.  I proposed a workaround adding a section on menuconfig to user increase delay (patch) but other developer proposed another patch to configure this delay at runtime rather than at compile time. This patches weren’ t  applied to mainline (to further information check link). I decided post here because I take some time to configure my NFS  rootfs due this delay. My tests were made using BeagleBoard and USB-Ethernet dongle based on ASIX 8877x.

fev
23
2010

Uploads de fotos no Flickr! usando API e Python

A API (Interface de Programação de Aplicativo) do Flickr! é bem documetada e rapidamente você pode fazer bastante coisa. Se você desejar usar a linguagem Python como método de acesso, em linhas gerais você precisa.

  1. Criar uma chave na API do Flickr!
  2. Download do binding para acesso a API (flickrapi)

Nas distribuições Linux, um dos jeitos de instalar é usar o easy_install

easy_install flickrapi

Um modo eficaz para fazer o upload das fotos no serviço seria um script que varre e submete todas as imagens, por exemplo, de uma pasta definida. O exemplo abaixo recebe como parâmetro um diretório e busca por todos os arquivos com extensão .jpg. A função status é apenas para mostrar o andamento do upload e é executada como uma chamada callback no método flickr.upload(). Nos meus testes, precisei pegar o número definido na variável token, antes, executando na interface de linha de comando do Python os seguintes passos:

>>> api_key = "<API>"
>>> secret = "<CHAVE SECRETA>"
>>> username = "<USER>"
>>> flickr = flickrapi.FlickrAPI(api_key,secret,username)
>>> (token, frob) = flickr.get_token_part_one(perms="write")
>>> print token
>>> print frob

Na hora o browser padrão irá abrir e pedir para você confirmar o uso do aplicativo.

# -*- coding: utf-8 -*-
#/bin/python 
 
import sys
import glob 
import flickrapi
 
api_key = "<API>"
secret = "<CHAVE SECRETA>"
username = "<USER>"
 
token="<TOKEN>"
frob=None
 
def status(progress, done):
	if done:
		print "Finished ;-)"
	else:
		print "At %s%%" % progress
 
def upload(photo):
	flickr.upload(photo, callback=status)
 
if __name__ == "__main__":
 
        flickr = flickrapi.FlickrAPI(api_key,secret,username)
        flickr.get_token_part_two((token,frob))
 
        photos = sys.argv[1]+"*.jpg"
 
	for photo in glob.glob(photos):
		print "Uploading: ",photo
		upload(photo)

Um exemplo de uso:

python upload.py /Fotos

Utilize sua criatividade para extender essa idéia e criar aplicativos que ensinem e facilite sua vida. :-)

fev
21
2010

Problems updating intltool on Gentoo

If you are experiencing some problems on updating dev-util/intltool on Gentoo, this is the message that is shown:

checking for perl… /usr/bin/perl
checking for perl >= 5.8.1… 5.10.1
checking for XML::Parser… configure: error: XML::Parser perl module is required for intltool

In other emerges if its failing on some perl module check during ./configure, its maybe because dev-lang/perl was updated an its modules weren’t compiled against the new one, on my case I just runned the command:

perl-cleaner --all

It will rebuild all your modules against your new perl, then you can re-emerge dev-util/intltool.

fev
19
2010

Adicionando SSH Fingerprints automaticamente ao known_hosts

Olá,
Da mesma série de posts sobre automatização de configurações da pasta do usuário (nossa, pra quem não postava, já esta até fazendo série de posts heheh). Iremos abordar uma configuração que muitas vezes nos trás muita dor de cabeça, aceitar todos fingerprints de chaves de servidor ssh.

Eu costumo utilizar o $HOME/.ssh/config para deixar todos meus hosts ssh configurados, pra quem não conhece isso, basta criar este arquivo, e ele usa o seguinte formato:

Host <nome servidor>
HostName <host/ip>
User <usuário>

realizando a configuração de um servidor fictício:

Host servidor
HostName localhost
User root

Feito isto, basta digitar: ssh servidor, que seria o equivalente a ssh root@localhost, isto facilita quando não se tem acesso ao /etc/hosts para guardar nome amigável para determinados ips, e quando se acessa diferentes servidores com diferentes nomes de usuários. Voltando ao nosso problema, eu tenho meu config, mas meu known_hosts esta desatualizado ou pior, vazio!

A cada nova conexão seria necessário aceitar cada chave do servidor, como a seguir:

The authenticity of host ’servidor (127.0.0.1)’ can’t be established.
RSA key fingerprint is bc:b1:8d:c3:61:6a:5b:9f:c1:b2:16:c5:e4:d2:b1:b2.
Are you sure you want to continue connecting (yes/no)?

O que torna cansativo, principalmente se tiver que executar um comando em cada servidor, então temos o seguinte script:

KNOWN_HOSTS=./ssh_known_hosts
SSH_ARGS="-o StrictHostKeyChecking=no -o UserKnownHostsFile=$KNOWN_HOSTS"
 
for host in `cat $HOME/.ssh/config |grep "^Host "|cut -d" " -f2`; do
    echo $host;
    ssh $host $SSH_ARGS echo '';
done
 
cnt=1
for host in `cat $HOME/.ssh/config |grep "^Host "|cut -d" " -f2`; do
    linha1=`sed "${cnt}q;d" $KNOWN_HOSTS`
    echo $linha1 $host &gt;&gt; ${KNOWN_HOSTS}.tmp
    echo "" &gt;&gt; ${KNOWN_HOSTS}.tmp
    let cnt++
done
 
mv ${KNOWN_HOSTS}.tmp ${KNOWN_HOSTS}

O que este script faz, nada mais é do que ler cada Host configurado no arquivo $HOME/.ssh/config e aceitar automaticamente a chave primária do mesmo através da opção -o StrictHostKeyChecking=no e salva no arquivo -o UserKnownHostsFile=$KNOWN_HOSTS (no nosso caso KNOWN_HOSTS=./ssh_known_hosts), fiz isso para não sobrescrever o seu arquivo known_hosts e ainda para facilitar a leitura do arquivo, ou pegar somente os hosts que lhe interessam, o segundo for do script coloca o valor do ‘Host’ como comentário em cada fingerprint.

Vale a pena lembrar que cada chave será automaticamente aceita, então cabe a você garantir que realmente cada chave pertence ao servidor em questão, e não esta ocorrendo nenhum tipo de ataque man-in-the-middle. E após executado o script, é só colocar os fingerprints no known_hosts e estamos prontos para conectar no servidor sem confirmação dos mesmos.

Até breve.

fev
17
2010

Kernel stats: horários dos commits

Durante sua apresentação na Linux.conf.au 2010, o fundador do site LWN.net e contribuidor do kernel Jonathan Corbet demonstrou uma análise das contribuições no kernel Linux durante aproximadamente 1 ano (entre Dez 2008 e Jan 2010). Uma das conclusões é que 75% código é escrito por programadores pagos por empresas, lideram a lista: Red Hat (12%), Intel (8%), IBM e Novell (6% cada), Oracle (3%).

Um dos pontos que a estatística não mostra é que – mesmo sendo empregado de grandes empresas – boa parte do trabalho é feita fora do horário “comercial”, se alguém observar as datas de todos os commits e organizá-los pela frequência em horas, você tem o seguinte resultado para diferentes releases.

v2.6.33-rc7		v2.6.32			  v2.6.24	

Hora	Commits		Hora	Commits		Hora	Commits
0	8069		0	7808		0	4745
1	7052		1	6800		1	4155
2	4715		2	4556		2	2835
3	2717		3	2601		3	1395
4	2236		4	2096		4	898
5	1426		5	1193		5	559
6	1299		6	1134		6	381
7	1933		7	1723		7	580
8	4108		8	3798		8	1445
9	6429		9	6003		9	2261
10	8550		10	7969		10	3027
11	10284		11	9640		11	3946
12	9191		12	8403		12	3313
13	11728		13	11024		13	4522
14	13127		14	12340		14	5052
15	14281		15	13295		15	5813
16	13685		16	12721		16	5212
17	11486		17	10793		17	5050
18	7938		18	7334		18	3335
19	7354		19	6933		19	2850
20	7460		20	6953		20	3161
21	8561		21	8138		21	3436
22	8953		22	8498		22	3872
23	7741		23	7335		23	3843

Comando utilizado para gerar esses dados:

git log v2.6.33 | grep ^Date: | perl -pe ’s/^(?:\S+\s+){4}(\d+).*/$1/’ | sort -g | uniq -c

A conclusão é que muitos desenvolvedores fazem o código durante a noite e acordam tarde. ;-)