예제 #1
0
파일: worker.py 프로젝트: paolo-losi/msgbox
    def work(self):
        self.state = 'working'
        try:
            self._process_stored_sms()
        except Exception:
            logger.error('error while processing stored sms', exc_info=True)
            self.serial_manager.send(ShutdownNotification(self))
            return self.shutdown

        # TODO check imsi (sim hot swap)
            
        msg = self.receive(timeout=5)
        if isinstance(msg, StopActor):
            return self.shutdown
        elif isinstance(msg, SimConfigChanged):
            # FIXME
            return self.work
        elif isinstance(msg, Timeout):
            self._is_network_available
            return self.work
        elif isinstance(msg, TxSmsReq):
            self._send_sms(msg)
            return self.work
        else:
            logger.error('unexpected msg type %s', msg)
예제 #2
0
파일: worker.py 프로젝트: paolo-losi/msgbox
    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)
예제 #3
0
파일: serial.py 프로젝트: paolo-losi/msgbox
 def __init__(self, usb_only):
     self.usb_only = usb_only
     if usb_only and plat[:5] != 'linux':
         logger.error('--usb-only supported only on linux (ignored)')
         self.usb_only = False
     self.dev2worker = {}  # {'/dev/ttyS0': ModemHandler(), ...
     super(SerialPortManager, self).__init__('SerialPortManager')
예제 #4
0
파일: sim.py 프로젝트: paolo-losi/msgbox
 def shutdown(self):
     while True:
         msg = self.receive()
         if isinstance(msg, ChannelClosed):
             if self._shutdown_callback:
                 self._shutdown_callback()
                 break
         else:
             logger.error('unexpected msg %s', msg)
예제 #5
0
파일: worker.py 프로젝트: paolo-losi/msgbox
 def _send_sms(self, tx_sms):
     # TODO handle delivery report
     if not self._is_network_available:
         err_msg = '%s: network unavailable' % tx_sms
         tx_sms.callback(status('ERROR', err_msg))
         return
     try:
         self.modem.sendSms(tx_sms.recipient, tx_sms.text)
     except Exception, e:
         logger.error('error:', exc_info=True)
         tx_sms.callback(status('ERROR', '%s: %r' % (tx_sms, e)))
예제 #6
0
파일: worker.py 프로젝트: paolo-losi/msgbox
 def shutdown(self):
     self.state = 'shutting down'
     self._try_modem_close()
     self.concat_pool.stop()
     self.close_channel()
     msg = self.receive()
     if isinstance(msg, ChannelClosed):
         self._unregister()
         return None
     else:
         # FIXME there may be a queue of SMS txt requests
         logger.error('unexpected msg type %s', msg)
         return self.shutdown
예제 #7
0
파일: http.py 프로젝트: paolo-losi/msgbox
 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)
예제 #8
0
파일: worker.py 프로젝트: paolo-losi/msgbox
 def stop(self):
     if self.sim_config.active:
         self.state = 'waiting for config'
     else:
         self.state = 'stopped'
     msg = self.receive()
     if isinstance(msg, StopActor):
         return self.shutdown
     elif isinstance(msg, SimConfigChanged):
         # FIXME
         return self.work
     elif isinstance(msg, Timeout):
         return self.register
     elif isinstance(msg, TxSmsReq):
         self._send_sms_when_stopped(msg)
         return self.stop
     else:
         logger.error('unexpected msg type %s', msg)
         return self.stop
예제 #9
0
파일: main.py 프로젝트: paolo-losi/msgbox
                        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()