Il passaggio della ISS via RSS
Il programma che ho scritto nelle ultime ore, permette di creare dei feed RSS (quelli che si sottoscrivono solitamente per ricevere notizie da varie fonti) che ci informano del passaggo della ISS (ovvero della Stazione Spaziale Internazionale) sopra la nostra testa.
Una volta inseriti nel file i link reperibili sul sito dell ESA (Agenzia Spaziale Europea) il programma genererà i feed rss e li pubblicherà su un piccolo server web privato.
Il programma contiene molte opzioni, ed è facilmente configurabile (ho pure messo un discreto numero di
commenti stavolta
).
E importante (soprattutto se permettete agli altri di accedere al server web) creare una cartella adhoc dove posizionare il programma, in quanto verranno condivisi tutti i file e le cartelle presenti.
Il programma necessita della libreria BeautifulSoup.
Per qualsiasi dubbio o problema potete, come sempre, lasciarmi un commento.
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2011 Francesco Frassinelli # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ### Configurazione - Inizio # N.B.: Tutti i tempi sono espressi in secondi # Questa lista contiene tutti i link relativi alle posizioni # Link presi da: http://esa.heavens-above.com/countries.aspx # Per prendere un nuovo link bisogna: # 1. Andare su http://esa.heavens-above.com/countries.aspx # 2. Selezionare la nazione # 3. Digitare il nome del paese # 4. Premere Submit # 5. Premere sul link del paese (solitamente il primo a sinistra) # 6. Copiare il link ISS (si trova tra le previsioni a dieci giorni) # 7. Incollare il link nella lista sottostante, similmente agli altri urls = ( 'http://esa.heavens-above.com/PassSummary.aspx?satid=25544&lat=43.800&lng=7.650&loc=Vallecrosia&alt=53&tz=CET', 'http://esa.heavens-above.com/PassSummary.aspx?satid=25544&lat=43.950&lng=8.133%20&loc=Marina+di+Andora&alt=0&tz=CET', 'http://esa.heavens-above.com/PassSummary.aspx?satid=25544&lat=45.483&lng=9.367&loc=Vignate&alt=110&tz=CET', ) # A chi voui fare vedere i feed? # Impostare host su 0.0.0.0 per renderli visibili a tutti host = localhost # Porta del server # Su Unix solitamente le porte minori di 1024 sono riservate port = 1912 # Tempo di refresh dei feed interval = 60*60 # Tempo dell auto riavvio del server in caso di problemi di rete autoReboot = 60 # Le informazioni contenute in ogni elemento del feed # Puoi utilizzare tutte le parole chiave presenti in self.keys rssItem = ( ' <item> , ' <title>[%(date)s - %(start_time)s]' ' Magnitudine apparente: %(magnitude)s</title> , ' <description> , Evento di magnitude %(magnitude)s%(br)s , Inizio previsto alle %(start_time)s in direzione %(start_azimuth)s%(br)s , Altezza massima previta alle %(max_time)s in direzione %(max_azimuth)s%(br)s , Fine prevista alle %(end_time)s in direzione %(end_azimuth)s%(br)s , ' </description> , ' <link>%(link)s</link> , ' </item> , ) ### Configurazione - Fine from BeautifulSoup import BeautifulSoup from cgi import escape, parse_qs from os import devnull, execl from urllib2 import urlopen, urlparse from SimpleHTTPServer import SimpleHTTPRequestHandler from socket import error from SocketServer import TCPServer from sys import argv, executable, exit, stdout from threading import Thread, Event from time import localtime, sleep, strftime, strptime def debug(message): print( .join((strftime( [%d/%m/%y - %H:%M:%S] ), message))) class UpdateFeed(Thread): def __init__(self, urls, interval): Thread.__init__(self) self.event = Event() self.urls = urls self.interval = interval self.keys = [ magnitude , start_time , start_altitude , start_azimuth , max_time , max_altitude , max_azimuth , end_time , end_altitude , end_azimuth , ] self.tags = { br :escape('<br />')} def shutdown(self): self.event.set() def run(self): while 1: if self.event.isSet(): return self.task() self.event.wait(self.interval) def task(self): for url in self.urls: args = parse_qs(urlparse.urlparse(url).query) args = dict((key, value[0]) for key, value in args.iteritems()) name = [part.capitalize() for part in args[ loc ].split()] args[ loc ] = .join(name) data = self.getPasses(url, args) if data == None: break with open( %(loc)s.xml % args, wb ) as feed: self.xmlOutput(feed, data, args) debug( Aggiornato il feed %(loc)s.xml % args) def getPasses(self, url, args): try: raw = urlopen(url).read() except: debug( Errore di rete ) reboot() soup = BeautifulSoup(raw) for row in soup.findAll( tr , { class :[ lightrow , darkrow ]}): elements = row.findAll( td ) values = [item.string for item in elements[1:]] result = dict(zip(self.keys, values)) result[ date ] = elements[0].a.string escaped = escape(dict(row.td.a.attrs)[ href ]) result[ link ] = urlparse.urljoin(url, escaped) event = .join(( strftime( %Y ), args[ tz ], result[ date ], result[ end_time ] )) eventTime = strptime(event, %Y %Z %d %b %H:%M:%S ) if eventTime < localtime(): continue yield result def xmlOutput(self, feed, data, args): lines = ( '<?xml version="1.0" encoding="UTF-8"?> , '<rss version="2.0"' ' xmlns:atom="http://www.w3.org/2005/Atom"> , ' <atom:link href="http://dallas.example.com/rss.xml"' ' rel="self" type="application/rss+xml" /> ' <channel> , ' <title>Guarda la ISS da %(loc)s</title> , ' <link>http://frafra.eu</link> , ' <description>Tutti i passaggi visibili della ISS' ' nei prossimi dieci giorni</description> , ) feed.writelines((string % args for string in lines)) for result in data: result.update(self.tags) feed.writelines((string % result for string in rssItem)) feed.writelines(( ' </channel> , '</rss> , )) def startServer(host, port): httpd = TCPServer((host, port), SimpleHTTPRequestHandler) debug( Server attivo sulla porta %s aperto a %s % (port, host)) debug( Server disponibile su http://localhost:%s/ % port) httpd.serve_forever() def reboot(): debug( Riavvio il programma tra %d secondi % autoReboot) stdout = open(devnull, a ) try: sleep(autoReboot) except KeyboardInterrupt: debug( Programma terminato ) exit(1) python = executable execl(python, python, *argv) if __name__ == __main__ : refresh = UpdateFeed(urls, interval) refresh.start() try: startServer(host, port) except KeyboardInterrupt: debug( Server disattivato ) except error: debug( Errore nell attivazione del server ) reboot() finally: refresh.shutdown() debug( Programma terminato )
Il programma è abbastanza robusto, ma non va per il sottile se la connessione diventa instabile o non disponibile, ovvero si limita ad autoriavviarsi nella speranza che questa torni a funzionare.
Per chiuderlo, basta il classico [CTRL] + [C]
Per rimuovere i feed non più utilizzati, bisogna cancellare i relativi file *.xml.
Popularity: unranked [?]




![Validate my RSS feed [Valid RSS]](http://img88.imageshack.us/img88/339/validrssrogers.png)






In questi giorni ho abbandonato Evolution in seguito a svariati motivi di cui non voglio discutere in questo articolo ( anche perché molti sono puramente soggettivi ) per ritornare al vecchio e caro Thunderbird ( l’unico problema che ho dovuto risolvere era l’integrazione con il plugin del calendario Lightning, maledette libstdc++5!! ). Sistemata tutta la mia posta elettronica installo come lettore di news Liferea ( si anche Thunderbird legge le news ma ho sempre trovato Liferea molto più comodo e completo ), importo il file xml che avevo generato con Evolution e qui mi trovo di fronte ad un’amara visione. La finestra di Liferea diventa tutta grigia e sembra tutto bloccato.























