Controle de ponto usando dbus-monitor

Aqui no trabalho, a folha de ponto é registrada manualmente, usando uma planilha do Excel onde precisamos registrar as horas de entrada/saída. É arcaico, mas tem sido menos problemático do que o ponto eletrônico, que às vezes dava pane, engatava o rolo, acabava papel etc.

Pois bem, até recentemente, eu vinha coletando a hora de entrada/saída a partir dos logs de sistema da minha máquina (visto que quase sempre eu dou resume/suspend no início/fim do expediente). Mas às vezes eu não desligava a máquina e por isso não tinha aquele dia registrado. Tive então a ideia de monitorar as mensagens D-Bus que são enviadas quando faço o bloqueio/desbloqueio da tela. Para quem não sabe, o D-Bus é a ferramenta mais usada no Linux para comunicação entre processos (InterProcess Communication, IPC). Por exemplo, sempre que a tela é bloqueada, certa mensagem é enviada via D-Bus e os processos interessados ficam “ouvindo” por esta mensagem. O mesmo ocorre no desbloqueio.

Sem mais rodeios, este é o script que escrevi:

#!/bin/bash
dbus-monitor --profile \
"type=signal,path=/org/gnome/SessionManager/Presence,\
interface=org.gnome.SessionManager.Presence,\
member=StatusChanged" | \
awk '$7 != "NameAcquired"{system("date -d @"$2)}'

O dbus-monitor permite “ouvir” as mensagens D-Bus que foram autorizadas para o usuário. A opção --profile altera o formato da saída de modo que cada mensagem D-Bus seja expressa em uma linha. Exemplo de saída:

sig 1389965062 467981 2 /org/freedesktop/DBus org.freedesktop.DBus NameAcquired

Estamos interessados na segunda coluna, que é um “timestamp” que pode ser convertido para o dia/hora em que a mensagem foi recebida. No script, o comando date é usado para converter esse timestamp para uma data legível. Por exemplo, date -d @1389965062 gera Fri Jan 17 09:24:22 AMT 2014 no meu fuso horário (UTC-4).

O awk é uma poderosa ferramenta para filtrar e processar texto, especialmente se este tiver um formato tabular como o gerado pelo “dbus-monitor –profile”. No script, ele simplesmente lê a segunda coluna de cada linha e executa o comando “date” (como descrito acima) para converter o timestamp para uma data legível. Notem que ele exclui a linha onde a sétima coluna seja igual a “NameAcquired”. Essa linha sempre é gerada quando se inicia o dbus-monitor e não representa o evento que nos interessa. Para entender melhor o funcionamento do awk, sugiro ler o bom e velho manual.

Só resta explicar o significado do texto:

"type=signal,path=/org/gnome/SessionManager/Presence,\
interface=org.gnome.SessionManager.Presence,\
member=StatusChanged"

De acordo com o manual do dbus-monitor, esta é uma “watch expression”. Basicamente, é um filtro que descreve que tipo de mensagens queremos observar (as demais são ignoradas). Em português, a linha acima diz que estamos interessados em sinais (type=signal) cujo caminho seja /org/gnome/SessionManager/Presence, interface org.gnome.SessionManager.Presence e nome StatusChanged. Mais detalhes sobre o significado dos temos usados aqui podem ser encontrados no tutorial do D-Bus.

Faltou ainda explicar como eu uso o script. Por enquanto, eu inicio ele manualmente usando este comando (que pode ser digitado em qualquer terminal):

./scripts/track_login_logout.sh &>> ~/ponto.txt &

Usei algumas funcionalidades do shell que talvez não sejam do conhecimento geral, então vale explicar. “&>> ~/ponto.txt” siginifica “redirecione tanto a saída padrão como a saída de erro para o arquivo ~/ponto.txt. O “&” ao final da linha significa que o comando irá rodar em background, portanto a janela do terminal poderá ser fechada e o script continuará em execução.

Uma última observação: a mesma técnica pode ser usada para monitorar outras mensagens D-Bus, basta trocar a “watch expression”. A que eu usei depende do GNOME/Unity, e foi testado apenas no Ubuntu 12.04.

Posted in General, Portuguese | Tagged | Leave a comment

My blog in 2010

The stats helper monkeys at WordPress.com mulled over how this blog did in 2010, and here’s a high level summary of its overall blog health:

Healthy blog!

The Blog-Health-o-Meter™ reads Wow.

Crunchy numbers

Featured image

A helper monkey made this abstract painting, inspired by your stats.

About 3 million people visit the Taj Mahal every year. This blog was viewed about 30,000 times in 2010. If it were the Taj Mahal, it would take about 4 days for that many people to see it.

In 2010, there were 8 new posts, growing the total archive of this blog to 27 posts.

The busiest day of the year was August 27th with 328 views. The most popular post that day was Running PySide applications on Qt Simulator.

Where did they come from?

The top referring sites in 2010 were developer.symbian.org, maemo.org, labs.trolltech.com, labs.qt.nokia.com, and thezeroth.net.

Some visitors came searching, mostly for undefined reference to `vtable for, undefined reference to vtable, qt symbian linux, undefined reference to vtable for, and undefined reference to `vtable.

Attractions in 2010

These are the posts and pages that got the most views in 2010.

1

Running PySide applications on Qt Simulator August 2010
2 comments

2

Installing Qt for Symbian SDK 4.6.2 on Linux February 2010
44 comments and 1 Like on WordPress.com,

3

“undefined reference to `vtable for …’ errors” in Qt derived classes April 2009
8 comments

4

Installing Qt for Symbian SDK 4.6.1 on Linux January 2010
43 comments

5

Running Qt for S60 SDK on Linux July 2009
12 comments

Posted in General | Leave a comment

PySide 1.0.0~beta1 binaries released for Ubuntu

Didier ‘OdyX’ Raboud once again borrowed his great Debian packaging/integration skills to the PySide project, and created packages for the latest Ubuntu releases (including the development one, codenamed “natty”). They are available on the official repository. See the download instructions page for more details. See also the original announcement.

Posted in Debian/Ubuntu, Linux | Tagged , , , | Leave a comment

Qt 4.7.0 for Symbian on Linux (now with Qt Creator support!)

It’s been some time since my last update on the Qt for Symbian Linux installer. My colleague Bruno Abinader did a great job in the meantime, by releasing his own modified “all-in-one” script that installed gnupoc, Qt, Qt Mobility and Smart Installer :D.

From now on, I’ll follow Bruno’s idea and provide a single script that installs everything you need for Qt for Symbian development on Linux. This version will install just gnupoc and Qt, but next ones should support Qt Mobility and Smart Installer as well. I also temporarily disabled support for S60 3.1 SDK, so for now there is only S60 5.0 SDK support.

Some of you might have noticed that the official Qt 4.7.0 documentation has some experimental installation instructions for Linux. Unfortunately, it requires compiling Qt from sources, which might take long time and currently requires the non-free ARM RVCT compiler. The instructions on this post are my attempt on creating a usable setup in a user-friendly way.

So, enough explanations, let’s go to the instructions!

Preparation

Download all required files to a single directory (e.g. “~/downloads”):

For building the native tools from gnupoc, you will need:

  • the GCC C/C++ compilers
  • development files for zlib
  • development files for openssl

On Ubuntu, you can install these using the following command:

sudo apt-get install build-essential zlib1g-dev libssl-dev

Installation

Install everything using a single command:

./qt_for_symbian_4.7.0_linux_installer_v4.sh \
    <download-dir> \
    <install-dir>

Replace <download-dir> with the location of all files downloaded in previous section (e.g. “~/downloads”), and <install-dir> with the destination directory (e.g. “~/gnupoc”). Note that both directories must have absolute paths.

If installation was successful, you should see the message “Installation has finished!” followed by some instructions. Follow those to setup Qt Creator and/or command line.

Device setup

Install Qt on the phone, by copying and installing the <install-dir>/qt_4.7.0/qt_installer.sis package. This single SIS file has all necessary dependencies for running Qt applications.

Additionally, if you plan to use Qt Creator, I suggest installing s60_5_0_app_trk_3_2_7.sisx. It will allow quickly testing your application directly on the device through bluetooth. Also make sure your desktop and phone are paired, then run these commands:

sdptool browse local | grep -q "Service Name: Serial Port" \
  || sdptool add SP
sudo rfcomm listen rfcomm0

The first command makes sure the Serial Port service is only added once, and the second one creates the /dev/rfcomm0 device. You should see output like:

Serial Port service registered
Waiting for connection on channel 1

On the phone, open App TRK (It should be under the “RnD Tools” directory). It will show “Status: Not connected”. Go to Options -> Settings, and make sure “Connection” is set to “Bluetooth”. Next, go to Options -> Connect and select your desktop from the Bluetooth devices shown. On the phone, you should see:

Status: Connected
BT Dev Name: <your_computer_name>
BT Port number: 1

While on your desktop console:

...
Connection from XX:XX:XX:XX:XX:XX to /dev/rfcomm0
Press CTRL-C for hangup

Now, when you click “Run” on Qt Creator, you should see something like this on its “Console Window”:

Executable file: /home/lizardo/gnupoc/sdk_5.0/epoc32/release/$(PLATFORM)/$(TARGET)/animatedtiles.exe
Package: 117288 2010-10-11T11:43:23 /home/lizardo/NokiaQtSDK/Examples/4.6/animation/animatedtiles/animatedtiles.sis
Deploying application to 'Bluetooth device (/dev/rfcomm0)'...
Copying installation file...
Installing application...
Starting application...
Application running with pid 1134.

And the application should install and open directly on your phone :) Enjoy!

Posted in Linux | Tagged , , , | 34 Comments

Running PySide applications on Qt Simulator

Some may have noticed that the Nokia Qt SDK contains a simulator for Qt applications on Nokia devices. It consists of the simulator application, plus Qt libraries built for its platform (Q_WS_SIMULATOR), which basically “wraps” the target application on the simulator window (and allows to simulate various events of the target device).

It has been asked on the Maemo.org Talk whether it would be possible to run PySide applications on the simulator. Technically, it would be as simple as building PySide against the simulator libraries… and indeed it was! Well, at least after a couple of patches, I managed to make it work, as can be seen on the screenshot below (for the curious the application running on it is the “hyperui” demo from pyside-examples repository):

Qt Simulator running PySide

For anyone willing to try, you just need to download the latest PySide code, apply the patches not yet upstream (to the pyside.git tree), and build everything as per official instructions, with these notes:

  • When building PySide, add the directory which contains the Qt tools for the Simulator platform (usually “<SDK_installation_dir>/Simulator/Qt/gcc/bin”) to your PATH (taking care to add it before other directories which contain Qt tools).
  • When building PySide, add -DQ_WS_SIMULATOR=yes to the cmake command. This is necessary because currently CMake does not detect the Simulator platform, thus requiring us to force it.
  • When running applications, remember to set LD_LIBRARY_PATH to point to the Simulator libraries, otherwise the application might try to be run with your system Qt libraries, which will probably fail.

To make testing easier, I built PySide binaries (from git snapshots) for the Simulator libraries shipped in Nokia Qt SDK 1.0. You can download them here. They were built on Ubuntu 10.04 (32-bit), but will probably work on other (32-bit) distributions. Also note it was build for Python 2.6. To use these binaries, unpack the tarball and modify the “qt_sdk_dir” in run_with_simulator.sh to point to your Nokia Qt SDK installation directory. Next, run:

./run_with_simulator.sh /path/to/app.py

And your application should run under the simulator (the simulator opens automatically if not already running).

TODO

  • Apply required PySide patches upstream (they are currently under review).
  • Attempt to build PySide Mobility as well.
Posted in General | Tagged , , , | 5 Comments

Python bindings for Qt Mobility APIs now available

Are you a Python developer, feeling envious of your C++-coding buddies cranking out N900 Qt applications with all those nice Qt Mobility APIs? No reason for envy any longer: The PyMaemo/PySide team is proud to present PySide Mobility: Python bindings for the Qt Mobility APIs! Combining the power of Python and the Nokia-sponsored PySide Qt bindings with the capabilities of Qt Mobility, you’ll be spewing out impressive apps for N900 like never before!

Original announcement

Posted in General | Tagged , , , | Leave a comment

PySide for Maemo 5 rebuilt for Qt 4.6.2 final release

Qt 4.6.2 for Maemo 5 was released this week. Due to some changes prior to the final Qt release, PySide users might have seen this error when trying to use QtQui:

Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: /usr/lib/pymodules/python2.5/PySide/QtGui.so: undefined symbol: _ZNK24QAbstractKineticScroller10metaObjectEv

To fix this, we rebuilt the PySide 0.2.3 packages against the Qt 4.6.2 release, and now it should be working again. So make sure you are using the latest PySide packages on Maemo 5 (0.2.3-1maemo3) and enjoy!

Posted in General | Tagged , , , | 2 Comments