Example #1
0
 def _try_modem_close(self):
     if self.modem is not None:
         try:
             self.modem.close()
         except Exception, e:
             logger.info('error while closing modem: %s', e)
         finally:
Example #2
0
    def _rx_sms(self, sms):
        if isinstance(sms, ReceivedSms):
            try:
                number = convert_to_international(sms.number, sms.smsc)
            except Exception, e:
                logger.error('error while converting to int: %s', e)
                number = sms.number
            sms_dict = dict(sender=number,
                            recipient=self.sim_config.phone_number,
                            text=sms.text,
                            tstamp=sms.time,
                            url=self.sim_config.url)

            if sms.udh is not None:
                concats = [i for i in sms.udh if isinstance(i, Concatenation)]
                assert len(concats) <= 1
                if concats:
                    sms_dict['concat'] = concats[0]
                    logger.info('concat sms received - '
                                'sender=%s recipient=%s part=%d/%d',
                                 sms_dict['sender'],
                                 sms_dict['recipient'],
                                 sms_dict['concat'].number,
                                 sms_dict['concat'].parts)
                    concat_sms_dict = self.concat_pool.merge(sms_dict)
                    if concat_sms_dict:
                        http_client_manager.enqueue(concat_sms_dict)
                    return

            http_client_manager.enqueue(sms_dict)
Example #3
0
 def _load_dump(self):
     if os.path.exists(DUMP_FILE):
         with open(DUMP_FILE) as fin:
             data = json.load(fin)
             for d in data:
                 config = SimConfig.from_dict(d)
                 self._insert(config)
             logger.info('loaded config for %d sim card(s)', len(data))
     else:
         logger.info('config %s not found', DUMP_FILE)
Example #4
0
    def register(self, worker):
        imsi = worker.imsi
        assert imsi is not None
        if imsi in self.imsi2worker:
            if self.imsi2worker[imsi] == worker:
                success = True
            else:
                success = False
        else:
            logger.info('registered imsi "%s" -> dev "%s"', imsi, worker.dev)
            self.imsi2worker[imsi] = worker
            success = True

        if imsi not in self.sim_config_db:
            logger.info('new sim - imsi: %s', imsi)
            self.sim_config_db.add(imsi)
        config = self.sim_config_db[imsi]

        worker.send(ImsiRegistration(success, config))
Example #5
0
 def _work(self):
     while self.active or not self.queue.empty:
         try:
             msg_dict = self.queue.get(timeout=2)
         except Empty:
             continue
         url = msg_dict.pop("url")
         for attempt in xrange(3):
             try:
                 msg_dict["text"] = msg_dict["text"].encode("utf8")
                 data = urllib.urlencode(msg_dict)
                 urllib2.urlopen(url, data, timeout=20)
                 logger.info("forwarded sms - sender=%s recipient=%s", msg_dict["sender"], msg_dict["recipient"])
                 break
             except Exception, e:
                 logger.error("error while sending msg", exc_info=True)
             time.sleep(10)
         else:
             logger.error("giving up sending message %s", msg_dict, exc_info=1)
Example #6
0
 def run(self):
     while True:
         self.detect_serial_ports()
         msg = self.receive(timeout=5)
         if isinstance(msg, StopActor):
             for worker in self.dev2worker.itervalues():
                 logger.info('stopping worker for device %s', worker.dev)
                 worker.send(StopActor())
             self.dev2worker = {}
             break
         elif isinstance(msg, ShutdownNotification):
             worker = msg.worker
             assert self.dev2worker[worker.dev] == worker
             self.remove_worker(worker)
             logger.info('worker for device %s has shut down', worker.dev)
         elif isinstance(msg, Timeout):
             continue
         else:
             raise ValueError('unexpected msg type %s' % msg)
Example #7
0
    def route(self, msg):
        sender = msg.sender
        imsi   = msg.imsi
        sim_config = None

        if sender:
            sim_config = self.sim_config_db.route(sender)
        if sim_config is None and imsi in self.sim_config_db:
            sim_config = self.sim_config_db[imsi]
        if sim_config is None:
            err_msg = '%s: sim not known' % msg
            if msg.callback:
                msg.callback(status('ERROR', err_msg))
            return

        worker = self.imsi2worker.get(sim_config.imsi)
        if worker:
            logger.info('%s: routing to dev %s', msg, worker.dev)
            worker.send(msg)
        else:
            msg.callback(status('ERROR', '%s: sim not found' % msg))
Example #8
0
    def detect_serial_ports(self):
        serial_devices = set()
        for d in comports():
            dev, desc, hw = d
            if hw == 'n/a':
                continue
            if self.usb_only:
                base = os.path.basename(dev)
                if (not base.startswith('ttyACM') and
                    not base.startswith('ttyUSB')):
                    continue

            serial_devices.add(dev)

            if dev not in self.dev2worker:
                spi = SerialPortInfo(desc=desc, dev=dev, hw=hw)
                mw = ModemWorker(dev=dev, serial_info=spi, serial_manager=self)
                logger.info('starting worker for device %s', dev)
                mw.start()
                self.dev2worker[dev] = mw

        for dev in self.dev2worker.keys():
            if dev not in serial_devices:
                logger.info('active worker on missing device %s', dev)
Example #9
0
 def start(self):
     logger.info("http listening on port %s", self.port)
     self.http_server.listen(self.port)
Example #10
0
 def state(self, new_state):
     if hasattr(self, '_state') and new_state != self._state:
         logger.info('STATE %s -> %s', self._state, new_state)
     self._state = new_state
Example #11
0
                        format='[%(levelname)1.1s %(asctime)s] '
                               #'%(name)-15s '
                               '%(threadName)-20s '
                               '%(message)s')


    serial_manager = SerialPortManager(args.usb_only)

    http_client_manager.start()
    sim_manager.start()
    serial_manager.start()
    http_server_manager.start()
    try:
        tornado.ioloop.IOLoop.instance().start()
    except KeyboardInterrupt, SystemExit:
        pass
    except Exception:
        logger.error('error trapped', exc_info=True)
    finally:
        logger.info("shutting down ...")
        http_server_manager.stop()
        serial_manager.stop()
        sim_manager.stop(finalize_shutdown)


signal.signal(signal.SIGTERM, lambda sig, frame: sys.exit(0))


if __name__ == '__main__':
    main()