Archivio della categoria: PyS60

Python for the S60 Platform eLearning


A coloro che vogliono imparare la programmazione Python su Series 60, segnalo un tutorial appena pubblicato da Nokia sul portale dedicato agli sviluppatori:

Python for the S60 Platform eLearning

Altri riferimenti utili:

Infine, il mio progettino stupido di Blackout Alarm via SMS (da cui, però c’è ben poco da imparare).

PyS60 blackout alarm


(english translation follows – segue testo in inglese )

Ci sono applicazioni che richiedono un controllo costante dello stato della linea elettrica, per segnalare eventuali interruzioni. Può trattarsi di sistemi di ricarica per l’industria o, più semplicemente, della linea elettrica domestica dei nonni dai quali correre in aiuto in caso di blackout.

È davvero semplice realizzare un "allarme blackout" via SMS utilizzando un vecchio terminale Series 60 e Python. Io ho utilizzato un glorioso Nokia 6630, che appartiene alla Series 60 2nd Edition Feature Pack 2.

6630_pyblackout.jpg

Prima di tutto è necessario installare il runtime PyS60 per il terminale in uso. I file di installazione aggiornati si possono scaricare dalla pagina del progetto su sourceforge, mentre consiglio un ottimo tutorial sull’installazione del runtime e sulla programmazione Python su Series 60 scritto da Jurgen Scheible.

Il vantaggio nell’utilizzare un Series 60 2nd Edition rispetto ad uno più recente appartenente alla 3rd Edition è nella maggiore facilità di installazione degli script. Mentre nella terza edizione occorre creare una cartella "Python" della memory card e copiarvi gli script all’interno utilizzando OBEX FTP (purtroppo non supportato nativamente dai driver Bluetooth di Windows XP), il runtime della 2nd Edition consente di inviare gli script via OBEX Push e di installarli direttamente dalla message box.

Un vecchio terminale 2nd Edition con il suo caricatore, Python for S60 e poche linee di codice sono sufficienti a creare questa applicazione. L’idea è banale: il telefono è connesso al caricabatterie, che a sua volta è connesso alla rete elettrica domenistica; poichè via software è possibile sapere lo stato del caricatore (connesso, non connesso, in carica, scarico…), se quest’ultimo appare disconnesso (ovvero la batteria non è mantenuta in carica) significa che "manca la corrente" e dunque c’è un blackout.

Python consente di scrivere in poche righe questa applicazione: lo script comincia chiedendo all’utente il numero di telefono el destinatario del messaggio d’allarme, dunque provvede a controllare lo stato del charger ogni 10 secondi. Non appena il caricatore risulta non connesso, l’applicazione manda un SMS al numero di telefono indicato all’inizio. Finito!

Prima di poter eseguire il codice sul terminale, è necessario installare la libreria sysagent, che permette di accedere ad alcune funzioni a basso livello dell’hardware e del sistema operativo. Occorre inoltre installare lo script esysagent come libreria; questo script fornisce le costanti numeriche utilizzate da sysagent.

È possibile scaricare questi due file dal sito Cyke64 (link diretti: sysagentesysagent). Su questo interessante sito potete trovare anche uno script d’esempio che mostra come utilizzare le funzioni di sysagent.

L’installazione può avvenire trasferendo via Bluetooth i due file sul telefono e selezionando "Install as lib" quando richiesto:

sysagent_py.png

A questo punto il runtime PyS60 possiede tutto ciò che serve a fare questo allarme blackout:


import e32, messaging, appuifw
import sysagent, esysagent

recipient = appuifw.query(u"Recipient:", "text")

print "Checking power line..."

while True:
    print "Sleeping..."
    e32.ao_sleep(10)
    print "Checking status"
    if sysagent.charger_status() != esysagent.ESAChargerConnected:
        print "Powerline is down!"
        messaging.sms_send(recipient, u"Powerline is down!")
        break

print "Bye bye..."

Lo script comincia importando alcuni moduli: e32 (per la gestione dei thread), messaging (per l’invio del messaggio d’allarme), appuifw (per visualizzare una popup) e la coppia sysagent-esysagent (per leggere lo stato del caricatoe). La prima istruzione visualizza la popup dove digitare il numero del destinatario::


recipient = appuifw.query(u"Recipient:", "text")

pyblackout_recipient.png

Un ciclo while() infinito controlla ogni 10 secondi lo stato del caricatore. In realta’ il ciclo parte aspettando 10 secondi prima di fare il controllo, dando cosi’ il tempo di connettere il caricatore al cellulare e alla linea elettrica. Scaduta la sleep(), viene invocata la funzione sysagent.charger_status(), che restituisce lo stato del caricatore (connected, disconnected, not charging). Se il caricatore non e’ connesso:


sysagent.charger_status() != esysagent.ESAChargerConnected

lo script invia il messaggio. That’s all!

pyblackout_start.png

There are some applications which require to verify powerline status and to report any power down event. It could be a industrial recharging system and, simpler, the domestic line of your grandparents (that may get in panic in case of blackout).

It is very easy to build an SMS-based "blackout alarm system" using an old Series 60 device and Python. I used a Nokia 6630, which belongs to Series 60 2nd Edition Feature Pack 2.

6630_pyblackout.jpg

First of all you need to get and install the PyS60 runtime tailored for your device. You can find all files at sourceforge and get read detailed installation instructions at Jurgen Scheible’s tutorial. Main advantage of 2nd Edition compared to the 3rd Edition is the easier installation process of Python scripts. While on the latter you have to create a "Python" forlder on memory card and trasfer files using OBEX FTP, the 2nd Edition lets you install applications simply (OBEX) pushing scripts to the messaging box.

An old 2nd Edition device with its charger, Python for S60 and a few lines of code are enough to build a (very) simple blackout alarm system. The idea is simple. The phone is connected to its charger, which is connected to powerline: if the charger seems to be disconnected (the battery is not charging), it means that powerline is down and the phone has to send an alarm message.

Python code is straightforward: it starts querying the telephone number to receive alarm messages, then checks the charger status every 10 seconds. When the charger status is not connected, it sends an SMS to the telephone number previously specified. That’s all!

Before writing the code, you need to install the sysagent library, which provides interface to some lowlevel hw & os routines. You have also to install the esysagent script, which defines names for numeric constants used by sysagent.

You can download these files from Cyke64 web site (direct links: sysagentesysagent). On this site, you can find also a sample script that shows how to use sysagent routines.

You can install both by simply pushing them via Bluetooth and clicking on "Install as lib" when prompted:

sysagent_py.png

Now the PyS60 runtime has all the stuff required to read charger status. Here’s the code:


import e32, messaging, appuifw
import sysagent, esysagent

recipient = appuifw.query(u"Recipient:", "text")

print "Checking power line..."

while True:
    print "Sleeping..."
    e32.ao_sleep(10)
    print "Checking status"
    if sysagent.charger_status() != esysagent.ESAChargerConnected:
        print "Powerline is down!"
        messaging.sms_send(recipient, u"Powerline is down!")
        break

print "Bye bye..."

The application stars importing some modules: e32 (for thread sleeping), messaging (for sending alarm messages), appuifw (to display the initial query popup) and sysagent-esysagent pair (to read charger status). The first instruction displays a popup where to type the phone number receiving alarm messages:


recipient = appuifw.query(u"Recipient:", "text")

pyblackout_recipient.png

An infinite while block checks every 10 seconds the status of powerline. The cycle starts pausing the application for 10 seconds (you have time to connect the handset to the charger, if it is still untethered). Then, it invokes the sysagent.charger_status() method, which returns the status of charger (connected, disconnected, not charging). If the charger appears not to be connected (sysagent.charger_status() != esysagent.ESAChargerConnected), the script sends a message to the recipient provided at startup.

pyblackout_start.png

Save your Series 60!


These days I’ve been thinking about objects obsolescence. All manufacturers improve their products (ranging from electronic devices to cars), giving us the perception that any old product (that is, what we’ve bought just some weeks ago) is obsolete. Upcoming products are faster, simpler, cheaper, beautiful as no other previously released. In a word: better. Even if we don’t need to change what we previously get (it still works as good as expected), new features are provided only by new models and keeping old ones implies to miss new possibilities. Implications can be surprisingly strong. Think about cars: some municipalities prohibit city access to cars not compliant with Euro 4 specification. Something similar happens with computers: new applications may require most recent operating systems, that require new hardware (that luckly doesn’t require you to update your house to get it!).

Obsolescence is pervasive in the mobile phone market. Not only manufacturers improve performances of hansets, fueling them with faster connections, larger displays and huge memory capacity; they also transform mobile phones in "fashion objects", as clothes or jewels. Developers know that just one or two new models per year are actually revolutionary: the others are just well-known-old-phones with a different case and name.

Obsolescence invokes update, which produces disposing: any time we update our devices with new models, we usually have to dispose obsolete items. For a limited time, we may try to keep both… but… after a while, we will prefer one (usually the newer!), so that the other will be disposed (usually the older!). Considered that there are about 2 billions of mobile phones and that average lifetime of each is 23 months, we will have a lot of "small yet connected intelligent devices" ready to be disposed.

Is there any way to reuse and/or recycle them? Recycle (disassembling devices and ruse part of them as components for new devices) is not so easy; plastics and electronics have been designed and tailored to work together, to separate and reassemble them requires a complex integration plan. Reuse (use those devices as they are even for different applications) is more practicable for "common people". In general, reuse beats recycle. Reuse is feasible for devices that provide enough power (CPU, memory, communication facilities) to be programmed and interfaced with the rest of the world.

Not any mobile device can be reused as an embedded system. Many devices can’t be programmed, many others have so frustraing limitations that any idea dies before starting to write one line of code! :-(

Among others, Nokia Series 60 is one of the most used smartphone platforms. Handsets based on this platform, once announced, are considered as state-of-the-art devices for a certain period of time: high resolution displays, enhanced multimedia capabilities, extended communication interfaces, robust and mature programming environment with a rich set of languages and tools. Month after month, the finnish manufacturer invades the mobile phones market with new award-winning families of handsets. Series 60 was born with 7650, but maturity arrived with 6630 and N70. Most recent devices, based on the 3rd edition of the platform, are market leaders and new models will appear during the Mobile World Congress.

We are pleased to get new devices, but what happens to old Series 60? Unfortunately, they can’t compare with upcoming, styilish smartphones, which expose unbelieveble performances. However, they are still powerful enough to be used for anything but as phone! Can we consider Series 60 2nd edition handset just programmable devices with communication capabilities? I believe we can. There should be an initiative to encourage people (mostly developers) to reuse their Series 60 as "new" embedded devices instead of considering them as "obsolete" phones. Something like "Save your Series 60" (let’s say "SyS60"), would be an attempt to find a wait to avoid that 100 millions of Series 60 sold till the end of 2007 would be trashed in less than two years.

Thanks to my friend Davide, pioneer in mobile application development, I’ve been introduced to Python development on Series 60. I believe that Python for Series 60 is not suitable for industrial projects, for which Java Micro Edition or native C++ are still best solutions. In fact, JME portability and C++ performances are unbeatable. However, Python is excellent for fast prototyping, powerful as C++ and simpler than Java. Python can be the driver to “Save our Series 60” and reuse them as funny and useful devices.

I spent some hours playing with Python, it is funny as Davide said! :-) Take a look to this interesting PyS60 tutorial, by Jurgen Scheible.