class TrainObserver(object): """This class queries reiseauskunft.bahn.de at a fixed interval to for all trains that travel on the travel connections that are stored in the DatabaseBackend. It determines if Trains are delayed or not and stores the result in the DatabaseBackend. """ def __init__(self, databasePath): """Creates a new instance of TrainObserver. @param databasePath Path to the DatabaseBackend that shall be used for observation.""" self._db = DatabaseBackend(databasePath) self._interval = 1 * 60# query every two minutes self._lookAhead = 2 # query trains starting in two minutes self._connections = self._db.connectionsAsList() self._start() def _start(self): """Starts the observation process.""" lastTrains = [] #remembers the trains that were retrieved last time for i in range(len(self._connections)): lastTrains.append([]) firstRun = True while True: print "Checking", len(self._connections), "connections" concnt = 0 for c in self._connections: tmp = localtime(time() + self._lookAhead * 60) departure = strftime("%H:%M", tmp) date = strftime("%d.%m.%Y", localtime()) trains = getTrains(c[0], c[1], date, departure) tl = [] trainsToProcess = list(lastTrains[concnt]) for t in trains: tl.append(t) if not t.delay() is None: try: print "Detected delayed train: {0} -> {1} ({2}): {3}".\ format(t.start(), t.end(), t.product(), "Start: {0}, delay: {1}".format( t.departure(), t.delay())) except: pass self.trainProcessed(t, trainsToProcess) if not firstRun: # are there trains left to be processed? # if so, add them to the database, because they left the # station for t in trainsToProcess: print "Adding train ", t.start(), t.end(), t.departure() self._db.addTrain(t) lastTrains[concnt] = tl concnt += 1 firstRun = False sleep(self._interval) self._connections = self._db.connectionsAsList() def trainProcessed(self, train, trains): """Checks if the train, that is processed is in the list of trains that are expected to be processed. If so, it is removed from the list. """ for t in trains: if t.departure() == train.departure() and\ t.start() == train.start() and\ t.end() == train.end(): trains.remove(t) return