Permalink
Browse files

removed pygsm-gateway and spun it off to its on installable package i…

…n requirements.txt
  • Loading branch information...
1 parent ebfa3fe commit 350038e14c6f36d3717a3282090d4657aac161d8 Anders Hofstee committed Mar 8, 2012
No changes.
View
@@ -1,240 +0,0 @@
-import time
-import copy
-import Queue
-import urllib
-import urllib2
-import logging
-import threading
-
-import pygsm
-
-logger = logging.getLogger('pygsm_gateway.gsm')
-
-
-class GsmPollingThread(threading.Thread):
- _title = "pyGSM"
-
- # number of seconds to wait between
- # polling the modem for incoming SMS
- POLL_INTERVAL = 5
-
- # time to wait for the start method to
- # complete before assuming that it failed
- MAX_CONNECT_TIME = 10
-
- def __init__(self, url, url_args, modem_args):
- self.url = url
- self.url_args = url_args
- self.modem_kwargs = modem_args
- self.modem = None
-
- # set a default timeout if it wasn't specified in localsettings.py;
- # otherwise read() will hang forever if the modem is powered off
- if "timeout" not in self.modem_kwargs:
- self.modem_kwargs["timeout"] = '10'
- super(GsmPollingThread, self).__init__()
-
-
- def _wait_for_modem(self):
- """
- Blocks until this backend has connected to and initialized the modem,
- waiting for a maximum of self.MAX_CONNECT_TIME (default=10) seconds.
- Returns true when modem is ready, or false if it times out.
- """
-
- # if the modem isn't present yet, this message is probably being sent by
- # an application during startup from the main thread, before this thread
- # has connected to the modem. block for a short while before giving up.
- for n in range(0, self.MAX_CONNECT_TIME*10):
- if self.modem is not None: return True
- time.sleep(0.1)
-
- # timed out. we're still not connected
- # this is bad news, but not fatal, so warn
- logger.warning("Timed out while waiting for modem")
- return False
-
-
- def get_inbox_ids(self,):
- """
- For figuring out message box size
- """
-
- boxdata = self.modem.query('AT+CMGD=?')
-
- if "error" in boxdata.lower():
- print "Error - phone not supported"
- exit()
-
- message_ids = boxdata.split("(")[1].split(")")[0].split("-")[0].split(',')
-
- logger.debug('SIM Inbox size: %s message ids: %s' % (message_ids.__len__(), message_ids))
-
- return message_ids
-
-
- def clean_up_inbox(self,):
- """
- The Clean up / delete every message routine
- """
-
- message_ids = self.get_inbox_ids()
-
- for id in message_ids:
- try:
- self.modem.command('AT+CMGD=' + str(id))
- logger.debug('Cleaned read message %s from inbox' % i)
- except:
- pass
-
-
- def send(self, identity, text):
-
- # if this message is being sent from the start method of
- # an app (which is run in the main thread), this backend
- # may not have had time to start up yet. wait for it
- if not self._wait_for_modem():
- return False
-
- # attempt to send the message
- # failure is bad, but not fatal
- if str(identity).startswith('+') == False:
- identity = '+' + str(identity)
- was_sent = self.modem.send_sms(str(identity), text)
-
- if was_sent:
- self.sent_messages += 1
- else:
- self.failed_messages += 1
-
- return was_sent
-
-
- def message(self, identity, text):
- """ handle SMS from modem """
- url_args = copy.copy(self.url_args)
- url_args['identity'] = identity
- url_args['text'] = text
-
- # For compatibility with rapidsms-httprouter
- url_args['backend'] = 'console'
- url_args['sender'] = identity
- url_args['message'] = text
-
- try:
- # First we try a GET for httprouter
- logger.debug('Opening URL: %s' % self.url)
- response = urllib2.urlopen(self.url + '/?' + urllib.urlencode(url_args)) # This does a GET and likes httprouter
- except urllib2.HTTPError:
- # If that doesn't work we try a POST for threadless
- try:
- response = urllib2.urlopen(self.url, urllib.urlencode(url_args)) # This does a POST and likes threadlessrouter
- except Exception, e:
- logger.exception(e)
- return False
- except Exception, e:
- logger.exception(e)
- return False
-
- logger.info('SENT')
- logger.debug('response: %s' % response.read())
-
- def gsm_log(self, modem, str, level):
- logger.debug("%s: %s" % (level, str))
-
- def status(self):
-
- # abort if the modem isn't connected
- # yet. there's no status to fetch
- if not self._wait_for_modem():
- return None
-
- csq = self.modem.signal_strength()
-
- # convert the "real" signal
- # strength into a 0-4 scale
- if not csq: level = 0
- elif csq >= 30: level = 4
- elif csq >= 20: level = 3
- elif csq >= 10: level = 2
- else: level = 1
-
- vars = {
- "_signal": level,
- "_title": self.title,
- "Messages Sent": self.sent_messages,
- "Messages Received": self.received_messages }
-
- # pygsm can return the name of the network
- # operator since b19cf3. add it if we can
- if hasattr(self.modem, "network"):
- vars["Network Operator"] = self.modem.network
-
- return vars
-
- def start(self):
- try:
- self.sent_messages = 0
- self.failed_messages = 0
- self.received_messages = 0
-
- logger.info("Connecting and booting via pyGSM...")
- self.modem = pygsm.GsmModem(logger=self.gsm_log,
- **self.modem_kwargs)
- self.modem.boot()
-
- # Clean up (delete) all read messages from the SIM so it doesn't get filled up.
- # Don't do this unless we can't be both clever and on schedule
- # self.clean_up_inbox() # we're attempting to be clever (see above comment)
-
- if getattr(self, 'service_center', None) is not None:
- self.modem.service_center = self.service_center
- except:
- logger.exception('Caught exception booting modem')
- self.stop()
- raise
-
- # Now that the modem has been booted, start the thread
- super(GsmPollingThread, self).start()
-
- def run(self):
- try:
- self.running = True
- while self.running:
- logger.info("Polling modem for messages")
- msg = self.modem.next_message()
-
- if msg is not None:
- self.received_messages += 1
-
- # we got an sms! hand it off to the
- # router to be dispatched to the apps
- success = self.message(msg.sender, msg.text)
-
- # if the message was processed successfully remove it from the sim card
- if success != False:
- id = self.get_inbox_ids().pop(0)
- self.modem.command('AT+CMGD=' + str(id))
- logger.debug("Deleted message id: %s" % id)
-
- # wait for POLL_INTERVAL seconds before continuing
- # (in a slightly bizarre way, to ensure that we abort
- # as soon as possible when the backend is asked to stop)
- for n in range(0, self.POLL_INTERVAL*10):
- if not self.running: return None
- time.sleep(0.1)
- except:
- logger.exception('Caught exception in GSM polling loop')
- raise
- finally:
- self.stop()
-
- logger.info("Run loop terminated.")
-
- def stop(self):
-
- self.running = False
-
- # disconnect from modem
- if self.modem is not None:
- self.modem.disconnect()
View
@@ -1,48 +0,0 @@
-from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
-from SocketServer import ThreadingMixIn
-import threading
-import cgi
-from urlparse import urlparse, parse_qs
-import logging
-
-logger = logging.getLogger('pygsm_gateway.http')
-
-class PygsmHttpServer(ThreadingMixIn, HTTPServer):
- """Handle requests in a separate thread."""
-
- def __init__(self, address, send_method):
- class Handler(BaseHTTPRequestHandler):
- _send_method = send_method
- def do_POST(self):
- logger.debug('got POST')
- form = cgi.FieldStorage(
- fp=self.rfile,
- headers=self.headers,
- environ={'REQUEST_METHOD': 'POST',
- 'CONTENT_TYPE': self.headers['Content-Type'],
- })
- if 'identity' in form and 'text' in form:
- self._send_method(form['identity'].value,
- form['text'].value)
- self.send_response(200)
- else:
- self.send_response(400)
- self.end_headers()
- self.wfile.write('\n')
- return
-
- #added to play nicely with rapidsms_httprouter, although this perhaps is semantically incorrect.
- def do_GET(self):
- logger.debug('got GET')
- form = parse_qs(urlparse(self.path).query)
- if 'identity' in form and 'text' in form:
- self._send_method(form['identity'][0],
- form['text'][0])
- self.send_response(200)
- else:
- self.send_response(400)
- self.end_headers()
- self.wfile.write('\n')
- return
-
- HTTPServer.__init__(self, address, Handler)
@@ -1,24 +0,0 @@
-<html>
- <head>
- </head>
- <body>
-
- <div>
- <h2> Test POST </h2>
- <form method='POST' action='http://127.0.0.1:8080/'>
- <input type='text' name='identity'>
- <input type='text' name='text'>
- <input type='submit' value='send'>
- </form>
- </div>
-
- <div>
- <h2> Test GET </h2>
- <form method='GET' action='http://127.0.0.1:8080/'>
- <input type='text' name='identity'>
- <input type='text' name='text'>
- <input type='submit' value='send'>
- </form>
- </div>
- </body>
-</html>
@@ -1,54 +0,0 @@
-#!/usr/bin/env python
-import logging
-
-from http import PygsmHttpServer
-from gsm import GsmPollingThread
-from serial.tools.list_ports import *
-import platform
-
-
-logger = logging.getLogger()
-logger.addHandler(logging.StreamHandler())
-logger.setLevel(logging.INFO)
-
-fabulaws_logger = logging.getLogger('pygsm_gateway')
-fabulaws_logger.setLevel(logging.DEBUG)
-
-
-WINDOWS_NAME = 'nt'
-HUAWEI_NAME = 'PC UI Interface'
-
-
-if os.name == WINDOWS_NAME:
- for c in comports():
- if c[1].find('PC UI Interface') != -1:
- port = c[0]
-elif platform.platform().startswith('Darwin'):
- port = '/dev/tty.HUAWEIMobile-Modem'
-else:
- port = '/dev/tty.USB1'
-
-if __name__ == '__main__':
- args = {
- #'url': 'http://localhost:8000/backend/pygsm-gateway/',
- 'url' : 'http://localhost:8000/router/receive',
- 'url_args': {},
- 'modem_args': {
- 'port': port,
- 'baudrate': 115200,
- 'rtscts': 1,
- 'timeout': 10,
- }
- }
- gsm_thread = GsmPollingThread(**args)
- gsm_thread.start()
-
- server = PygsmHttpServer(('localhost', 8080), gsm_thread.send)
- print 'Starting server, use <Ctrl-C> to stop'
- try:
- server.serve_forever()
- except:
- raise
- finally:
- gsm_thread.running = False
- gsm_thread.join()
View
@@ -1,9 +1,3 @@
--e git://github.com/macdhuibh/rapidsms.git#egg=RapidSMS
--e git://github.com/rapidsms/pygsm.git#egg=pygsm
--e git://github.com/catalpainternational/rapidsms-xforms.git#egg=rapidsms-xforms
--e git://github.com/unicefuganda/rapidsms-generic.git#egg=rapidsms-generic
--e git://github.com/unicefuganda/rapidsms-contact.git#egg=rapidsms-contact
--e git://github.com/caktus/pygsm-gateway.git#egg=pygsm-gateway
django
django-sorting
django_pagination
@@ -14,3 +8,11 @@ django_wsgiserver
django_extensions
werkzeug
phonenumbers
+-e git://github.com/rapidsms/pygsm.git#egg=pygsm
+-e git://github.com/macdhuibh/rapidsms.git#egg=RapidSMS
+-e git://github.com/catalpainternational/code_generator#egg=code_generator
+-e git://github.com/catalpainternational/pygsm-gateway.git#egg=pygsm-gateway
+-e git://github.com/catalpainternational/rapidsms-xforms.git#egg=rapidsms-xforms
+-e git://github.com/unicefuganda/rapidsms-generic.git#egg=rapidsms-generic
+-e git://github.com/unicefuganda/rapidsms-contact.git#egg=rapidsms-contact
+

0 comments on commit 350038e

Please sign in to comment.