Ejemplo n.º 1
0
    def testMaxMessageArgs(self):
        # this device is much more complicated than
        # most, so is tucked away in mock.device
        device = MockSenderDevice()
        gsmPDU = pygsm.GsmModem(device=device, mode="PDU")
        gsmTEXT = pygsm.GsmModem(device=device, mode="TEXT")

        for gsm in (gsmPDU, gsmTEXT):
            # test with no max_message arg
            gsm.send_sms("1234", "Test Message")
            self.assertEqual(device.sent_messages[0]["recipient"], "21")
            self.assertEqual(device.sent_messages[0]["text"],
                             "00110004A821430000AA0CD4F29C0E6A96E7F3F0B90C")

            # test with reasonable max_message arg, should have no impact
            gsm.send_sms("1234", "Test Message", max_messages=20)
            self.assertEqual(device.sent_messages[0]["recipient"], "21")
            self.assertEqual(device.sent_messages[0]["text"],
                             "00110004A821430000AA0CD4F29C0E6A96E7F3F0B90C")

            # test with max_message = 0, should internally set to 1 with no problems
            gsm.send_sms("1234", "Test Message", -1)
            self.assertEqual(device.sent_messages[0]["recipient"], "21")
            self.assertEqual(device.sent_messages[0]["text"],
                             "00110004A821430000AA0CD4F29C0E6A96E7F3F0B90C")

            # test with max_message > 255, should internally force to 255
            gsm.send_sms("1234", "Test Message", 1024)
            self.assertEqual(device.sent_messages[0]["recipient"], "21")
            self.assertEqual(device.sent_messages[0]["text"],
                             "00110004A821430000AA0CD4F29C0E6A96E7F3F0B90C")

        # test with max_message = 1 and message too long to fit
        # should throw a value exception
        #
        # ONLY SUPPORTED IN PDU MODE, so run on PDU configured gsmmodem only
        msg = """
        0123456789012345678901234567890123456789012345678901234567890123456789
        0123456789012345678901234567890123456789012345678901234567890123456789
        0123456789012345678901234567890123456789012345678901234567890123456789
        0123456789012345678901234567890123456789012345678901234567890123456789
        0123456789012345678901234567890123456789012345678901234567890123456789
        0123456789012345678901234567890123456789012345678901234567890123456789
        0123456789012345678901234567890123456789012345678901234567890123456789
        """
        try:
            gsmPDU.send_sms("1234", msg, max_messages=1)
        except ValueError:
            print "ValueError caught"
        else:
            # Should have thrown an error!
            self.assertTrue(False)  # SMS too big should throw ValueError
Ejemplo n.º 2
0
class SMSServer:
    def __init__(self, config=None):
        '''
          Initialize GsmModem (calling the constructor calls .boot() on
          the object), start message_watcher thread and initialize variables
        '''
        try:
            self.parse_config()
        except Exception, e:
            print e
            raw_input("Press any key to continue")
        if not os.path.exists('slingshotsms.db'):
            self.reset()
        if self.mock_modem == False:
            try:
                self.modem = pygsm.GsmModem(port=self.port,
                                            baudrate=self.baudrate)
            except Exception, e:
                try:
                    self.modem = pygsm.AutoGsmModem()
                except GsmModemNotFound, e:
                    raw_input(
                        "No modems were autodetected - you will need to edit \
                            slingshotsms.txt to point Slingshot at your working GSM modem."
                    )
                    sys.exit()
Ejemplo n.º 3
0
    def start(self):
        self.modem = pygsm.GsmModem(
            *self.modem_args,
            **self.modem_kwargs)

        # If we got the connection, call superclass to
        # start the run loop--it just sets self._running to True
        # and calls run.
        if self.modem is not None:
            backend.Backend.start(self)
Ejemplo n.º 4
0
    def testSendSmsTextMode(self):
        """Checks that the GsmModem in TEXT mode accepts outgoing SMS,
           when the text is within ASCII chars 22 - 126."""

        # this device is much more complicated than
        # most, so is tucked away in mock.device
        device = MockSenderDevice()
        gsm = pygsm.GsmModem(device=device, mode="TEXT")

        # send an sms, and check that it arrived safely
        gsm.send_sms("1234", "Test Message")
        self.assertEqual(device.sent_messages[0]["recipient"], "1234")
        self.assertEqual(device.sent_messages[0]["text"], "Test Message")
Ejemplo n.º 5
0
    def testSendSmsPDUMode(self):
        """Checks that the GsmModem in PDU mode accepts outgoing SMS,
           when the text is within ASCII chars 22 - 126."""

        # this device is much more complicated than
        # most, so is tucked away in mock.device
        device = MockSenderDevice()
        gsm = pygsm.GsmModem(device=device, mode="PDU")

        # send an sms, and check that it arrived safely
        gsm.send_sms("1234", "Test Message")
        self.assertEqual(device.sent_messages[0]["recipient"], "21")
        self.assertEqual(device.sent_messages[0]["text"],
                         "00110004A821430000AA0CD4F29C0E6A96E7F3F0B90C")
Ejemplo n.º 6
0
    def send_message_via_gsm(self, identity, message):
        backend = PersistantBackend.objects.get(title="pyGSM")

        try:
            conf = settings.RAPIDSMS_CONF["gsm"]

            modem = pygsm.GsmModem(port=conf['port'])
            modem.connect()
            modem.send_sms(identity, message)
            # do things at a reasonable pace
            time.sleep(.2)
            return True
        except KeyError:
            return settings.RAPIDSMS_CONF["gsm"]
    def start(self):
        self.modem = pygsm.GsmModem(
            *self.modem_args,
            **self.modem_kwargs)

        if self.modem is not None:

            # set the SMSC, if it was included in the config.
            if self.service_center is not None:
                self.modem.service_center = self.service_center

            # call superclass to start the run loop--it just sets
            # self._running to True and calls run.
            backend.Backend.start(self)
Ejemplo n.º 8
0
    def testRetryCommands(self):
        """Checks that the GsmModem automatically retries
           commands that fail with a CMS 515 error, and does
           not retry those that fail with other errors."""
        class MockBusyDevice(MockDevice):
            def __init__(self):
                MockDevice.__init__(self)
                self.last_cmd = None
                self.retried = []

            # this command is special (and totally made up)
            # it does not return 515 errors like the others
            def at_test(self, one):
                return True

            def process(self, cmd):

                # if this is the first time we've seen
                # this command, return a BUSY error to
                # (hopefully) prompt a retry
                if self.last_cmd != cmd:
                    self._output("+CMS ERROR: 515")
                    self.last_cmd = cmd
                    return None

                # the second time, note that this command was
                # retried, then fail. kind of anticlimatic
                self.retried.append(cmd)
                return False

        device = MockBusyDevice()
        gsm = pygsm.GsmModem(device=device)
        n = len(device.retried)

        # override the usual retry delay, to run the tests fast
        gsm.retry_delay = 0.01

        # boot the modem, and make sure that
        # some commands were retried (i won't
        # check _exactly_ how many, since we
        # change the boot sequence often)
        gsm.boot()
        self.assert_(len(device.retried) > n)

        # try the special AT+TEST command, which doesn't
        # fail - the number of retries shouldn't change
        n = len(device.retried)
        gsm.command("AT+TEST=1")
        self.assertEqual(len(device.retried), n)
Ejemplo n.º 9
0
    def testKnownOperatorkName(self):
        """Long operator names are returned as-is."""
        class MockCopsDevice(MockDevice):
            def process(self, cmd):

                # return a valid +COPS response for AT+COPS?, but error
                # for other commands (except built-in MockDevice stuff)
                if cmd == "AT+COPS?":
                    return self._respond('+COPS: 0,0,"MOCK-NETWORK",0')

                return False

        device = MockCopsDevice()
        gsm = pygsm.GsmModem(device=device)
        self.assertEqual(gsm.network, "MOCK-NETWORK")
Ejemplo n.º 10
0
    def start(self):

        print "initting modem: %s %s" % (self.modem_args, self.modem_kwargs)

        self.modem = pygsm.GsmModem(*self.modem_args,
                                    **self.modem_kwargs).boot()

        # set our service center
        self.modem.service_center = "+250788110333"

        # If we got the connection, call superclass to
        # start the run loop--it just sets self._running to True
        # and calls run.
        if self.modem is not None:
            backend.Backend.start(self)
Ejemplo n.º 11
0
    def testUnknownOperatorName(self):
        """Unknown or missing operator names return a status string."""
        class MockCopsDevice(MockDevice):
            def process(self, cmd):

                # return a valid +COPS response for AT+COPS?, but error
                # for other commands (except built-in MockDevice stuff)
                if cmd == "AT+COPS?":
                    return self._respond('+COPS: 0')

                return False

        device = MockCopsDevice()
        gsm = pygsm.GsmModem(device=device)
        self.assertEqual(gsm.network, "(Automatic)")
Ejemplo n.º 12
0
    def testEchoOff(self):
        """Checks that GsmModem disables echo at some point
           during boot, to simplify logging and processing."""
        class MockEchoDevice(MockDevice):
            def process(self, cmd):

                # raise and error for any
                # cmd other than ECHO OFF
                if cmd != "ATE0":
                    return False

                self.echo = False
                return True

        device = MockEchoDevice()
        gsm = pygsm.GsmModem(device=device)
        self.assertEqual(device.echo, False)
Ejemplo n.º 13
0
    def testUsefulErrors(self):
        """Checks that GsmModem attempts to enable useful errors
           during boot, to make the errors raised useful to humans.
           Many modems don't support this, but it's very useful."""
        class MockUsefulErrorsDevice(MockDevice):
            def __init__(self):
                MockDevice.__init__(self)
                self.useful_errors = False

            def at_cmee(self, error_mode):
                if error_mode == "1":
                    self.useful_errors = True
                    return True

                elif error_mode == "0":
                    self.useful_errors = False
                    return True

                # invalid mode
                return False

        device = MockUsefulErrorsDevice()
        gsm = pygsm.GsmModem(device=device)
        self.assertEqual(device.useful_errors, True)
Ejemplo n.º 14
0
    def setUp(self):
        self.mocker = mox.Mox()
        self.mockDevice = self.mocker.CreateMock(
            pygsm.devicewrapper.DeviceWrapper)

        # verify the config commands
        self.mockDevice.write("ATE0\r")
        self.mockDevice.read_lines(**self.rl_args).AndReturn(self.ok)

        self.mockDevice.write("AT+CMEE=1\r")
        self.mockDevice.read_lines(**self.rl_args).AndReturn(self.ok)

        self.mockDevice.write("AT+WIND=0\r")
        self.mockDevice.read_lines(**self.rl_args).AndReturn(self.ok)

        self.mockDevice.write("AT+CSMS=1\r")
        self.mockDevice.read_lines(**self.rl_args).AndReturn(self.ok)

        # must see command to set PDU mode
        mode_int = self.mode_map[self.get_mode().lower()]
        self.mockDevice.write("AT+CMGF=%d\r" % mode_int)

        self.mockDevice.read_lines(**self.rl_args).AndReturn(self.ok)

        self.mockDevice.write("AT+CNMI=2,2,0,0,0\r")
        self.mockDevice.read_lines(**self.rl_args).AndReturn(self.ok)

        # verify fetch_stored_messages in boot
        cmgl_str = self.cmgl_map[self.get_mode().lower()]
        self.mockDevice.write("AT+CMGL=%s\r" % cmgl_str)
        self.mockDevice.read_lines(**self.rl_args).AndReturn(self.ok)

        self.mocker.ReplayAll()
        self.gsm = pygsm.GsmModem(device=self.mockDevice, mode=self.get_mode())

        self.mocker.ResetAll()
Ejemplo n.º 15
0
def logModems():
    networks = []
    for m in modem_config:
        print "Starting %s modem..." % m['name']
        modem = pygsm.GsmModem(port=m['port'],
                               baudrate=m['baudrate'],
                               logger=pygsm.GsmModem.debug_logger).boot()
        #modem.send_sms(ADMIN_NUMBER,"%s hello world!" % m['name'])
        networks.append({'name': m['name'], 'number': m['number'], \
                'sent_count': 0, 'received_count': 0,
                'modem': modem, 'send_to_self': m['send_to_self']})

    timer = 0
    global messages_to_send
    while True:
        print "Next sending in %s seconds" % (SEND_INTERVAL -
                                              (timer % SEND_INTERVAL))
        for n in networks:
            try:
                print "about to read message on %s modem" % n['name']
                msg = n['modem'].next_message()
                if msg is not None:
                    print "splitting message rec by %s..." % n['name']
                    msg_data = msg.text.split('*')
                    logfile = open('smslog.csv', 'a')
                    if len(msg_data) is 7:
                        n['received_count'] += 1
                        delay = getDelay(msg_data[4], msg_data[5])
                        print "   writing log file ..."
                        logfile.write(
                            "\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s %s\",\"%s\ %s\",\"%s\",\"%s\",\"%s\"\n"
                            % (msg_data[0], msg_data[1], msg_data[2],
                               msg_data[3], n['received_count'], msg_data[4],
                               msg_data[5], datetime.now().date(),
                               datetime.now().time(), delay, msg_data[6],
                               n['modem'].signal_strength()))
                    else:
                        logfile.write(
                            "\"Malformed message to %s modem\",\"%s\",\"%s\"\n"
                            % (n['name'], msg.text, datetime.now()))
                    logfile.close()
            except:
                print "   failed!"
                logfile = open('smslog.csv', 'a')
                logfile.write("read error for network %s\n" % n['name'])
                logfile.close()
        if messages_to_send:
            route = messages_to_send.pop()
            sendFromModems(route)
        if timer % SEND_INTERVAL == 0:
            print "Timer is %s, queueing messages to send" % timer
            populateSendQueue(networks)
            print "Deleting stored messages"
            for m in networks:
                for i in range(1, 41):
                    try:
                        m['modem'].command('AT+CMGD=' + str(i))
                        print("    +++deleted message from %s index %s" %
                              (m['name'], i))
                    except:
                        print(
                            "    ---failed to delete message from %s index %s"
                            % (m['name'], i))
        time.sleep(2)
        timer += 2
Ejemplo n.º 16
0
#modem.send_sms("9935648569", "Hey!")

table = s3db.msg_sms_modem_channel
modem_configs = db(table.enabled == True).select(
    table.modem_port,
    table.modem_baud,
)

# PyGSM GsmModem class instances
modems = []

for modem in modem_configs:
    # mode is set to text as PDU mode is flaky
    modems.append(
        pygsm.GsmModem(port=modem.modem_port,
                       baudrate=modem.modem_baud,
                       mode="text"))

if len(modems) == 0:
    # If no modem is found try autoconfiguring - We shouldn't do this anymore
    #try:
    #  modems.append(pygsm.AutoGsmModem())
    #except GsmModemNotFound, e:
    #  # No way yet to pass back the error yet
    #  pass
    pass
else:
    # Starting a thread for each modem we have
    for modem in modems:
        ModemThread(modem).run()
Ejemplo n.º 17
0
 def connect_modem_on_port(self, port):
     log.msg("Attempting modem on port %s" % port)
     self.modem = pygsm.GsmModem(port=port, mode="text", logger=self.logger)
     self.modem.boot()
     self.modem.incoming_queue = load_queue_from_disk(self.queue_file)
     self.wait_for_network()
import serial
import os, time
import pygsm
import tinydb
from tinydb import where, Query  # Comment :THIS WILL IMPORT THE tinydb database
db = tinydb.TinyDB(
    'ashlesha.json')  # Comment : name the database as ashlesha.json
myquery = Query()

#db.purge()
#db.all()
###############################################################################
################################ GSM RELATED CODES HERE #######################

gsm = pygsm.GsmModem(port="/dev/ttyUSB0").boot()
a = gsm.wait_for_network()


def delsms():
    for i in range(1, 5):
        gsm.command("AT+CMGD={0}".format(i))
        print 'deleting...', i
        time.sleep(1)


#port = serial.Serial("/dev/ttyUSB0", baudrate=9600, timeout=1)	#port number information to be put here, in case of raspberry pi, it'll be ttyUSB0
#port.write("\x1A") # Enable to send SMS

sms = " "

################################################################################
Ejemplo n.º 19
0
    def testWritesNothingDuringInit(self):
        """Nothing is written to the modem during __init__"""

        device = MockDevice()
        gsm = pygsm.GsmModem(device=device)
        self.assertEqual(device.buf_write, [])