Esempio n. 1
0
    def test_sms(self):
        state_machine = self.get_statemachine()
        status = state_machine.GetSMSStatus()

        remain = (status['SIMUsed'] + status['PhoneUsed'] +
                  status['TemplatesUsed'])

        self.assertEqual(remain, 6)

        start = True

        sms = []

        while remain > 0:
            if start:
                sms.append(state_machine.GetNextSMS(Start=True, Folder=0))
                start = False
            else:
                sms.append(
                    state_machine.GetNextSMS(Location=sms[-1][0]['Location'],
                                             Folder=0))
            remain = remain - len(sms)

        data = gammu.LinkSMS(sms)

        for item in data:
            message = gammu.DecodeSMS(item)
            if message is None:
                self.assertEqual(item[0]['UDH']['Type'], 'NoUDH')
Esempio n. 2
0
def ProcessMessages(list, synced):
    read = []
    unread = []
    sent = []
    unsent = []
    data = gammu.LinkSMS(list)

    for x in data:
        i = {}
        v = gammu.DecodeSMS(x)
        i['SMS'] = x
        if v is not None:
            i['SMSInfo'] = v
        ParseMessage(i, (v is not None))
        i['Synced'] = synced
        if i['State'] == 'Read':
            read.append(i)
        elif i['State'] == 'UnRead':
            unread.append(i)
        elif i['State'] == 'Sent':
            sent.append(i)
        elif i['State'] == 'UnSent':
            unsent.append(i)

    return {'read': read, 'unread': unread, 'sent': sent, 'unsent': unsent}
Esempio n. 3
0
def getAndDeleteAllSMS(state_machine):
    # Read SMS memory status ...
    memory = state_machine.GetSMSStatus()
    # ... and calculate number of messages
    remaining = memory["SIMUsed"] + memory["PhoneUsed"]

    # Get all sms
    start = True
    entries = list()

    try:
        while remaining > 0:
            if start:
                entry = state_machine.GetNextSMS(Folder=0, Start=True)
                start = False
            else:
                entry = state_machine.GetNextSMS(Folder=0,
                                                 Location=entry[0]["Location"])

            remaining = remaining - 1
            entries.append(entry)

            # delete retrieved sms
            state_machine.DeleteSMS(Folder=0, Location=entry[0]["Location"])

    except gammu.ERR_EMPTY:
        # error is raised if memory is empty (this induces wrong reported
        # memory status)
        print('Failed to read messages!')

    # Link all SMS when there are concatenated messages
    entries = gammu.LinkSMS(entries)

    return entries
Esempio n. 4
0
def getAndDeleteAllSMS(myStMa):
    # Read SMS memory status ...
    memory = myStMa.GetSMSStatus()
    # ... and calculate number of messages
    numMessages = memory["SIMUsed"] + memory["PhoneUsed"]

    # Get all sms
    start = True
    entriesAll = list()

    try:
        while numMessages > 0:
            if start:
                entry = myStMa.GetNextSMS(Folder=0, Start=True)
                start = False
            else:
                entry = myStMa.GetNextSMS(Folder=0,
                                          Location=entry[0]["Location"])

            numMessages = numMessages - 1
            entriesAll.append(entry)

            # delete retrieved sms
            myStMa.DeleteSMS(Folder=0, Location=entry[0]["Location"])

    except gammu.ERR_EMPTY:
        # error is raised if memory is empty (this induces wrong reportet memory
        # status)
        pass

    # Link all SMS when there are concatenated messages
    entriesAll = gammu.LinkSMS(entriesAll)

    return (entriesAll)
Esempio n. 5
0
def link_all_sms(sms, folders):
    data = gammu.LinkSMS([[msg] for msg in sms])

    for x in data:
        v = gammu.DecodeSMS(x)

        m = x[0]
        print_sms_header(m, folders)
        loc = []
        for m in x:
            loc.append(str(m['Location']))
        print('%-15s: %s' % ('Location(s)', ', '.join(loc)))
        if v is None:
            print('\n%s' % m['Text'].encode('utf-8'))
        else:
            for e in v['Entries']:
                print()
                print('%-15s: %s' % ('Type', e['ID']))
                if e['Bitmap'] is not None:
                    for bmp in e['Bitmap']:
                        print('Bitmap:')
                        for row in bmp['XPM'][3:]:
                            print(row)
                    print()
                if e['Buffer'] is not None:
                    print('Text:')
                    print(e['Buffer'].encode('utf-8'))
                    print()
Esempio n. 6
0
def loop_sms_receive():

    # process Received SMS
    allsms = []
    start = True
    while True:
        try:
            if start:
                sms = gammusm.GetNextSMS(Folder=0, Start=True)
                start = False
            else:
                sms = gammusm.GetNextSMS(Folder=0, Location=sms[0]['Location'])
            allsms.append(sms)
        except gammu.ERR_EMPTY as e:
            break

    if not len(allsms):
        return

    alllinkedsms = gammu.LinkSMS(allsms)

    for sms in alllinkedsms:
        if sms[0]['UDH']['Type'] == 'NoUDH':
            message = {
                "datetime": str(sms[0]['DateTime']),
                "number": sms[0]['Number'],
                "text": sms[0]['Text']
            }
            payload = json.dumps(message, ensure_ascii=False)
            client.publish(f"{mqttprefix}/received", payload)
            logging.info(payload)
            gammusm.DeleteSMS(Folder=0, Location=sms[0]['Location'])
        elif sms[0]['UDH']['AllParts'] != -1:
            if len(sms) == sms[0]['UDH']['AllParts']:
                decodedsms = gammu.DecodeSMS(sms)
                message = {
                    "datetime": str(sms[0]['DateTime']),
                    "number": sms[0]['Number'],
                    "text": decodedsms['Entries'][0]['Buffer']
                }
                payload = json.dumps(message, ensure_ascii=False)
                client.publish(f"{mqttprefix}/received", payload)
                logging.info(payload)
                for part in sms:
                    gammusm.DeleteSMS(Folder=0, Location=part['Location'])
            else:
                logging.info(
                    f"Incomplete Multipart SMS ({len(sms)}/{sms[0]['UDH']['AllParts']}): waiting for parts"
                )
        else:
            logging.info(
                '***************** Unsupported SMS type *****************')
            logging.info('===============sms=================')
            logging.info(sms)
            logging.info('===============decodedsms=================')
            decodedsms = gammu.DecodeSMS(sms)
            logging.info(decodedsms)
            logging.info('================================')
            gammusm.DeleteSMS(Folder=0, Location=sms[0]['Location'])
Esempio n. 7
0
    def get_and_delete_all_sms(self, state_machine, force=False):
        """Read and delete all SMS in the modem."""
        # Read SMS memory status ...
        memory = state_machine.GetSMSStatus()
        # ... and calculate number of messages
        remaining = memory["SIMUsed"] + memory["PhoneUsed"]
        start_remaining = remaining
        # Get all sms
        start = True
        entries = []
        all_parts = -1
        all_parts_arrived = False
        _LOGGER.debug("Start remaining:%i", start_remaining)

        try:
            while remaining > 0:
                if start:
                    entry = state_machine.GetNextSMS(Folder=0, Start=True)
                    all_parts = entry[0]["UDH"]["AllParts"]
                    part_number = entry[0]["UDH"]["PartNumber"]
                    is_single_part = all_parts == 0
                    is_multi_part = 0 <= all_parts < start_remaining
                    _LOGGER.debug("All parts:%i", all_parts)
                    _LOGGER.debug("Part Number:%i", part_number)
                    _LOGGER.debug("Remaining:%i", remaining)
                    all_parts_arrived = is_multi_part or is_single_part
                    _LOGGER.debug("Start all_parts_arrived:%s",
                                  all_parts_arrived)
                    start = False
                else:
                    entry = state_machine.GetNextSMS(
                        Folder=0, Location=entry[0]["Location"])

                if all_parts_arrived or force:
                    remaining = remaining - 1
                    entries.append(entry)

                    # delete retrieved sms
                    _LOGGER.debug("Deleting message")
                    try:
                        state_machine.DeleteSMS(Folder=0,
                                                Location=entry[0]["Location"])
                    except gammu.ERR_MEMORY_NOT_AVAILABLE:
                        _LOGGER.error(
                            "Error deleting SMS, memory not available")
                else:
                    _LOGGER.debug("Not all parts have arrived")
                    break

        except gammu.ERR_EMPTY:
            # error is raised if memory is empty (this induces wrong reported
            # memory status)
            _LOGGER.info("Failed to read messages!")

        # Link all SMS when there are concatenated messages
        entries = gammu.LinkSMS(entries)

        return entries
def retrieveAllSms(machine):
    status = machine.GetSMSStatus()
    allMultiPartSmsCount = status['SIMUsed'] + status['PhoneUsed'] + status[
        'TemplatesUsed']

    allMultiPartSms = []
    start = True

    while len(allMultiPartSms) < allMultiPartSmsCount:
        if start:
            currentMultiPartSms = machine.GetNextSMS(Start=True, Folder=0)
            start = False
        else:
            currentMultiPartSms = machine.GetNextSMS(
                Location=currentMultiPartSms[0]['Location'], Folder=0)
        allMultiPartSms.append(currentMultiPartSms)

    allSms = gammu.LinkSMS(allMultiPartSms)

    results = []
    for sms in allSms:
        smsPart = sms[0]

        result = {
            "Date": str(smsPart['DateTime']),
            "Number": smsPart['Number'],
            "State": smsPart['State'],
            "Locations": [smsPart['Location'] for smsPart in sms],
        }

        decodedSms = gammu.DecodeSMS(sms)
        if decodedSms == None:
            result["Text"] = smsPart['Text']
        else:
            text = ""
            for entry in decodedSms['Entries']:
                if entry['Buffer'] != None:
                    text += entry['Buffer']

            result["Text"] = text

        results.append(result)

        # Save list of received messages in a CSV file
        if save and result["State"] == "UnRead":
            fichier = open("/data/received.csv", "a")
            fichier.write(result["Date"] + ";" +
                          datetime.now().strftime("%Y-%m-%d %H:%M:%S") + ";" +
                          result["Number"] + ";\"" +
                          (result["Text"].replace("\n", "\\n").
                           replace("\"", "\"\"") if result["Text"] else "") +
                          "\"\n")
            fichier.close()
        #####################################

    return results
Esempio n. 9
0
def pdudecode(request):
    decoded = None
    smsinfo = None
    if request.method == "POST":
        form = PDUDecodeForm(request.POST)
        if form.is_valid():
            # Decode PDU
            decoded = []
            parts = []
            for i, part in enumerate(form.cleaned_data["text"].split()):
                try:
                    d = gammu.DecodePDU(binascii.unhexlify(part))
                    parts.append([d])
                    if isinstance(d["Text"], bytes):
                        d["TextHex"] = d["Text"].hex()
                    else:
                        d["TextHex"] = None
                    d["UDH"]["TextHex"] = d["UDH"]["Text"].hex()
                    d["Id"] = i + 1
                    d["PDU"] = part
                    decoded.append(d)
                except gammu.GSMError as e:
                    decoded.append({"Error": e.args[0]})
                except Exception as e:
                    decoded.append({"Error": {"Text": str(e)}})
            # Link multipart messages
            linked = gammu.LinkSMS(parts)
            # Decode multipart messages
            smsinfo = []
            part = 1
            for x in linked:
                try:
                    d = gammu.DecodeSMS(x)
                    if d is not None:
                        d["Id"] = part
                        part = part + 1
                        smsinfo.append(d)
                except UnicodeDecodeError as err:
                    smsinfo.append({
                        "Error": str(err),
                        "Id": part,
                        "Unknown": True
                    })
                    part = part + 1

    else:
        form = PDUDecodeForm()
    return render(
        request,
        "tools/pdudecode.html",
        {
            "form": form,
            "decoded": decoded,
            "smsinfo": smsinfo,
        },
    )
Esempio n. 10
0
def check_incoming_SMS():
    global consecutive_check_failures
    global last_try_OK
    try:
        status = sm.GetSMSStatus()
        last_try_OK = True
        remain = status['SIMUsed'] + status['PhoneUsed'] + status[
            'TemplatesUsed']
        if (remain > 0):
            sms = []
            start = True
            while remain > 0:
                if start:
                    cursms = sm.GetNextSMS(Start=True, Folder=0)
                    start = False
                else:
                    cursms = sm.GetNextSMS(Location=cursms[0]['Location'],
                                           Folder=0)
                remain = remain - len(cursms)
                sms.append(cursms)
            data = gammu.LinkSMS(sms)
            for x in data:
                gammu.DecodeSMS(x)
                m = x[0]
                log.info("new SMS received from %s: %s" %
                         (m['Number'], m['Text']))
                send_to_logbook("INFO",
                                "SMS received from " + str(m['Number']))
                if (m['Number'] in allowed_msisdn):
                    # TODO: exploiter les SMS en arrivée
                    pass
                else:
                    log.warning("%s is not allowed to send SMS to Basecamp!" %
                                m['Number'])
                    send_to_logbook(
                        "WARNING",
                        str(m['Number']) +
                        " not authorized to send SMS to BASECAMP!")
                # now delete it
                sm.DeleteSMS(0, m['Location'])
    except Exception as e:
        print(e.__str__())
        log.error(e)
        log.warning("could not check incoming SMS! :s")
        if last_try_OK is not True:
            consecutive_check_failures = consecutive_check_failures + 1
            if consecutive_check_failures == max_failed_SMS_checks:
                send_to_logbook(
                    "WARNING", "Could'nt check incoming SMS - " +
                    str(max_failed_SMS_checks) + " times in a row!")
                consecutive_check_failures = 0
        else:
            last_try_OK = False
    t = Timer(20.0, check_incoming_SMS)
    t.start()
Esempio n. 11
0
def read_sms_cb(data, remaining_calls):
    try:
        status = sm.GetSMSStatus()
    except gammu.ERR_TIMEOUT as e:
        weechat.prnt('', "%s%s" % (weechat.prefix("error"), e))
        return weechat.WEECHAT_RC_ERROR

    remain = status['SIMUsed'] + status['PhoneUsed'] + status['TemplatesUsed']
    sms = []
    start = True

    try:
        while remain > 0:
            if start:
                cursms = sm.GetNextSMS(Start=True, Folder=0)
                start = False
            else:
                cursms = sm.GetNextSMS(Location=cursms[0]['Location'],
                                       Folder=0)
            remain = remain - len(cursms)
            sms.append(cursms)
    except gammu.ERR_EMPTY:
        pass

    data = gammu.LinkSMS(sms)

    for x in data:
        v = gammu.DecodeSMS(x)

        m = x[0]
        sms_number = m['Number']

        contact = sms_number
        for name, number in contacts_dict.iteritems():
            if number == sms_number:
                contact = name
                break
        if v is None:
            message = unicodedata.normalize('NFKD', m['Text']).encode(
                'ascii', 'ignore')
        else:
            for e in v['Entries']:
                if e['Buffer'] != None:
                    message = unicodedata.normalize('NFKD',
                                                    e['Buffer']).encode(
                                                        'ascii', 'ignore')
        weechat.prnt(smsbuffer, "<- %s: %s" % (contact, message))

        # Delete SMS
        loc = []
        for m in x:
            sm.DeleteSMS(m['Folder'], m['Location'])
    return weechat.WEECHAT_RC_OK
Esempio n. 12
0
def pdudecode(request):
    decoded = None
    smsinfo = None
    if request.method == 'POST':
        form = PDUDecodeForm(request.POST)
        if form.is_valid():
            # Decode PDU
            decoded = []
            parts = []
            for i, part in enumerate(form.cleaned_data['text'].split()):
                try:
                    d = gammu.DecodePDU(binascii.unhexlify(part))
                    parts.append([d])
                    if isinstance(d['Text'], bytes):
                        d['TextHex'] = d['Text'].hex()
                    else:
                        d['TextHex'] = None
                    d['UDH']['TextHex'] = d['UDH']['Text'].hex()
                    d['Id'] = i + 1
                    d['PDU'] = part
                    decoded.append(d)
                except gammu.GSMError as e:
                    decoded.append({'Error': e.args[0]})
                except Exception as e:
                    decoded.append({'Error': {'Text': str(e)}})
            # Link multipart messages
            linked = gammu.LinkSMS(parts)
            # Decode multipart messages
            smsinfo = []
            part = 1
            for x in linked:
                try:
                    d = gammu.DecodeSMS(x)
                    if d is not None:
                        d['Id'] = part
                        part = part + 1
                        smsinfo.append(d)
                except UnicodeDecodeError as err:
                    smsinfo.append({
                        "Error": str(err),
                        "Id": part,
                        "Unknown": True
                    })
                    part = part + 1

    else:
        form = PDUDecodeForm()
    return render(request, 'tools/pdudecode.html', {
        'form': form,
        'decoded': decoded,
        'smsinfo': smsinfo,
    })
def main():
    if len(sys.argv) != 2:
        print('This requires parameter: backup file!')
        sys.exit(1)

    charsetencoder = codecs.getencoder(sys.getdefaultencoding())

    filename = sys.argv[1]

    backup = gammu.ReadSMSBackup(filename)

    # Make nested array
    messages = [[message] for message in backup]

    data = gammu.LinkSMS(messages)

    for message in data:
        decoded = gammu.DecodeSMS(message)

        part = message[0]
        print()
        print('{0:<15}: {1}'.format('Number', part['Number']))
        print('{0:<15}: {1}'.format('Date', str(part['DateTime'])))
        print('{0:<15}: {1}'.format('State', part['State']))
        print('{0:<15}: {1}'.format('Folder', part['Folder']))
        print('{0:<15}: {1}'.format('Validity', part['SMSC']['Validity']))
        loc = []
        for part in message:
            loc.append(str(part['Location']))
        print('{0:<15}: {1}'.format('Location(s)', ', '.join(loc)))
        if decoded is None:
            print('\n{0}'.format(charsetencoder(part['Text'], 'replace')[0]))
        else:
            for entries in decoded['Entries']:
                print()
                print('{0:<15}: {1}'.format('Type', entries['ID']))
                if entries['Bitmap'] is not None:
                    for bmp in entries['Bitmap']:
                        print('Bitmap:')
                        for row in bmp['XPM'][3:]:
                            print(row)
                    print()
                if entries['Buffer'] is not None:
                    print('Text:')
                    print(charsetencoder(entries['Buffer'], 'replace'))
                    print()
Esempio n. 14
0
def retrieveAllSms(machine):
    status = machine.GetSMSStatus()
    allMultiPartSmsCount = status['SIMUsed'] + status['PhoneUsed'] + status[
        'TemplatesUsed']

    allMultiPartSms = []
    start = True

    while len(allMultiPartSms) < allMultiPartSmsCount:
        if start:
            currentMultiPartSms = machine.GetNextSMS(Start=True, Folder=0)
            start = False
        else:
            currentMultiPartSms = machine.GetNextSMS(
                Location=currentMultiPartSms[0]['Location'], Folder=0)
        allMultiPartSms.append(currentMultiPartSms)

    allSms = gammu.LinkSMS(allMultiPartSms)

    results = []
    for sms in allSms:
        smsPart = sms[0]

        result = {
            "Date": str(smsPart['DateTime']),
            "Number": smsPart['Number'],
            "State": smsPart['State'],
            "Locations": [smsPart['Location'] for smsPart in sms],
        }

        decodedSms = gammu.DecodeSMS(sms)
        if decodedSms == None:
            result["Text"] = smsPart['Text']
        else:
            text = ""
            for entry in decodedSms['Entries']:
                if entry['Buffer'] != None:
                    text += entry['Buffer']

            result["Text"] = text

        results.append(result)

    return results
Esempio n. 15
0
    def test_link(self):
        # SMS info about message
        smsinfo = {
            'Entries': [{
                'ID': 'ConcatenatedTextLong',
                'Buffer': MESSAGE
            }]
        }

        # encode SMS
        sms = gammu.EncodeSMS(smsinfo)

        # link SMS
        linked = gammu.LinkSMS([[sms[0]], [sms[1]]], True)

        # decode back SMS
        decodedsms = gammu.DecodeSMS(linked[0])

        # compare results
        self.assertTrue(decodedsms['Entries'][0]['Buffer'], MESSAGE)
Esempio n. 16
0
def sms_getall(sm):
    status = sm.GetSMSStatus()
    remain = status['SIMUsed'] + status['PhoneUsed'] + status['TemplatesUsed']
    sms = []
    start = True

    while remain > 0:
        if start:
            cursms = sm.GetNextSMS(Start=True, Folder=0)
            start = False
        else:
            cursms = sm.GetNextSMS(Location=cursms[0]['Location'], Folder=0)
        remain = remain - len(cursms)
        sms.append(cursms)

    data = gammu.LinkSMS(sms)

    for x in data:
        v = gammu.DecodeSMS(x)
        m = x[0]
        subj = '[SMS] %s' % (str(m['Text']).replace('\n', ' '))
        loc = []
        for m in x:
            loc.append(str(m['Location']))
        if v == None:
            body = m['Text']
        else:
            body = ''
            for e in v['Entries']:
                if e['Bitmap'] != None:
                    for bmp in e['Bitmap']:
                        body = body + 'Bitmap:'
                        for row in bmp['XPM'][3:]:
                            body = body + row
                    print
                if e['Buffer'] != None:
                    body = body + 'Text:'
                    body = body + e['Buffer']
        mail_send(subj, body, m['Number'])
        for l in loc:
            sms_del(sm, int(l), 1)
Esempio n. 17
0
def pdudecode(request):
    decoded = None
    smsinfo = None
    if request.method == 'POST':
        form = PDUDecodeForm(request.POST)
        if form.is_valid():
            # Decode PDU
            decoded = []
            parts = []
            for i, part in enumerate(form.cleaned_data['text'].split()):
                try:
                    d = gammu.DecodePDU(part.decode('hex'))
                    parts.append([d])
                    if type(d['Text']) == unicode:
                        d['TextHex'] = None
                    else:
                        d['TextHex'] = d['Text'].encode('hex')
                    d['UDH']['TextHex'] = d['UDH']['Text'].encode('hex')
                    d['Id'] = i + 1
                    d['PDU'] = part
                    decoded.append(d)
                except gammu.GSMError, e:
                    decoded.append({'Error': e[0]})
                except Exception, e:
                    decoded.append({'Error': {'Text': str(e)}})
            # Link multipart messages
            linked = gammu.LinkSMS(parts)
            # Decode multipart messages
            smsinfo = []
            part = 1
            for x in linked:
                d = gammu.DecodeSMS(x)
                if d is not None:
                    d['Id'] = part
                    part = part + 1
                    smsinfo.append(d)
Esempio n. 18
0
def LinkAllSMS(sms, folders):
    data = gammu.LinkSMS([[msg] for msg in sms])

    for x in data:
        v = gammu.DecodeSMS(x)

        m = x[0]
        print
        print '%-15s: %s' % ('Number', m['Number'].encode('utf-8'))
        print '%-15s: %s' % ('Date', str(m['DateTime']))
        print '%-15s: %s' % ('State', m['State'])
        print '%-15s: %s %s (%d)' % ('Folder',
            folders[m['Folder']]['Name'].encode('utf-8'),
            folders[m['Folder']]['Memory'].encode('utf-8'),
            m['Folder'])
        print '%-15s: %s' % ('Validity', m['SMSC']['Validity'])
        loc = []
        for m in x:
            loc.append(str(m['Location']))
        print '%-15s: %s' % ('Location(s)', ', '.join(loc))
        if v == None:
            print '\n%s' % m['Text'].encode('utf-8')
        else:
            for e in v['Entries']:
                print
                print '%-15s: %s' % ('Type', e['ID'])
                if e['Bitmap'] != None:
                    for bmp in e['Bitmap']:
                        print 'Bitmap:'
                        for row in bmp['XPM'][3:]:
                            print row
                    print
                if e['Buffer'] != None:
                    print 'Text:'
                    print e['Buffer'].encode('utf-8')
                    print
Esempio n. 19
0
def sms_check(self):
    """Control and processing SMS"""
    try:
        import gammu
    except Exception:
        log.error(NAME,
                  _('SMS Modem plug-in') + ':\n' + traceback.format_exc())

    tel1 = sms_options['tel1']
    tel2 = sms_options['tel2']
    comm1 = sms_options['txt1']
    comm2 = sms_options['txt2']
    comm3 = sms_options['txt3']
    comm4 = sms_options['txt4']
    comm5 = sms_options['txt5']
    comm6 = sms_options['txt6']
    comm7 = sms_options['txt7']
    comm8 = sms_options['txt8']
    comm9 = sms_options['txt9']

    sm = gammu.StateMachine()
    sm.ReadConfig()
    try:
        sm.Init()
        log.debug(NAME, datetime_string() + ': ' + _('Checking SMS...'))
    except:
        log.error(NAME,
                  _('SMS Modem plug-in') + ':\n' + traceback.format_exc())
        self._sleep(60)

    if sms_options[
            "use_strength"]:  # print strength signal in status Window every check SMS
        signal = sm.GetSignalQuality(
        )  # list: SignalPercent, SignalStrength, BitErrorRate
        log.info(
            NAME,
            datetime_string() + ': ' + _('Signal') + ': ' +
            str(signal['SignalPercent']) + '% ' +
            str(signal['SignalStrength']) + 'dB')

    status = sm.GetSMSStatus()
    remain = status['SIMUsed'] + status['PhoneUsed'] + status['TemplatesUsed']
    sms = []
    start = True
    while remain > 0:
        if start:
            cursms = sm.GetNextSMS(Start=True, Folder=0)
            start = False
        else:
            cursms = sm.GetNextSMS(Location=cursms[0]['Location'], Folder=0)
        remain = remain - len(cursms)
        sms.append(cursms)
    data = gammu.LinkSMS(sms)
    for x in data:
        v = gammu.DecodeSMS(x)
        m = x[0]
        print '%-15s: %s' % ('Sender', m['Number'])
        print '%-15s: %s' % ('Date', str(m['DateTime']))
        print '%-15s: %s' % ('State', m['State'])
        print '%-15s: %s' % ('SMS command', m['Text'])
        if (m['Number']
                == tel1) or (m['Number']
                             == tel2):  # If telephone is admin 1 or admin 2
            log.info(NAME, datetime_string() + ': ' + _('SMS from admin'))
            if m['State'] == "UnRead":  # If SMS is unread
                log.clear(NAME)
                if m['Text'] == comm1:  # If command = comm1 (info - send SMS to admin phone1 and phone2)
                    log.info(
                        NAME,
                        _('Command') + ' ' + comm1 + ' ' + _('is processed'))
                    # send 1/2 SMS with text 1
                    up = helpers.uptime()
                    temp = helpers.get_cpu_temp(
                        options.temp_unit) + ' ' + options.temp_unit
                    ip = str(helpers.get_ip())
                    ver = version.ver_date
                    datastr = ('SMS 1/2. ' + datetime_string() + ', TEMP: ' +
                               temp + ', IP: ' + ip + ', SW: ' + ver +
                               ', UP: ' + up)
                    message = {
                        'Text': datastr,
                        'SMSC': {
                            'Location': 1
                        },
                        'Number': m['Number'],
                    }
                    sm.SendSMS(message)  # send sms 1/2
                    log.info(NAME, datastr)
                    # send 2/2 SMS with text 2
                    if inputs.rain_sensed():
                        rain = "Active"
                    else:
                        rain = "Inactive"
                    try:
                        from plugins import pressure_monitor
                        state_press = pressure_monitor.get_check_pressure()

                        if state_press:
                            press = "High"
                        else:
                            press = "Low"
                    except Exception:
                        press = "N/A"
                    finished = [
                        run for run in log.finished_runs()
                        if not run['blocked']
                    ]
                    if finished:
                        last_prog = finished[-1]['start'].strftime(
                            '%H:%M: ') + finished[-1]['program_name']
                    else:
                        last_prog = 'None'
                    datastr = ('SMS 2/2. ' + 'RAIN: ' + rain + ', PRESS: ' +
                               press + ', LAST: ' + last_prog)
                    message = {
                        'Text': datastr,
                        'SMSC': {
                            'Location': 1
                        },
                        'Number': m['Number'],
                    }
                    sm.SendSMS(message)  # send sms 2/2
                    log.info(NAME, datastr)

                    log.info(
                        NAME,
                        _('Command') + ': ' + comm1 + ' ' +
                        _('was processed and confirmation was sent as SMS to')
                        + ': ' + m['Number'])
                    sm.DeleteSMS(m['Folder'], m['Location'])  # SMS deleted
                    log.info(NAME, _('Received SMS was deleted'))

                elif m['Text'] == comm2:  # If command = comm2 (stop - scheduler)
                    log.info(
                        NAME,
                        _('Command') + ' ' + comm2 + ' ' + _('is processed'))
                    options.scheduler_enabled = False
                    log.finish_run(None)
                    stations.clear()

                    message = {
                        'Text': 'Command: ' + comm2 + ' was processed',
                        'SMSC': {
                            'Location': 1
                        },
                        'Number': m['Number'],
                    }
                    sm.SendSMS(message)
                    log.info(
                        NAME,
                        _('Command') + ': ' + comm2 + ' ' +
                        _('was processed and confirmation was sent as SMS to')
                        + ': ' + m['Number'])
                    sm.DeleteSMS(m['Folder'], m['Location'])
                    log.info(NAME, _('Received SMS was deleted'))

                elif m['Text'] == comm3:  # If command = comm3 (start - scheduler)
                    log.info(
                        NAME,
                        _('Command') + ' ' + comm3 + ' ' + _('is processed'))
                    options.scheduler_enabled = True
                    message = {
                        'Text': 'Command: ' + comm3 + ' was processed',
                        'SMSC': {
                            'Location': 1
                        },
                        'Number': m['Number'],
                    }
                    sm.SendSMS(message)
                    log.info(
                        NAME,
                        _('Command') + ': ' + comm3 + ' ' +
                        _('was processed and confirmation was sent as SMS to')
                        + ': ' + m['Number'])
                    sm.DeleteSMS(m['Folder'], m['Location'])
                    log.info(NAME, _('Received SMS was deleted'))

                elif m['Text'] == comm4:  # If command = comm4 (reboot system)
                    log.info(
                        NAME,
                        _('Command') + ' ' + comm4 + ' ' + _('is processed'))
                    message = {
                        'Text': 'Command: ' + comm4 + ' was processed',
                        'SMSC': {
                            'Location': 1
                        },
                        'Number': m['Number'],
                    }
                    sm.SendSMS(message)
                    log.info(
                        NAME,
                        _('Command') + ': ' + comm4 + ' ' +
                        _('was processed and confirmation was sent as SMS to')
                        + ': ' + m['Number'])
                    sm.DeleteSMS(m['Folder'], m['Location'])
                    log.info(
                        NAME,
                        _('Received SMS was deleted and system is now reboot'))
                    reboot()  # restart linux system

                elif m['Text'] == comm5:  # If command = comm5 (poweroff system)
                    log.info(
                        NAME,
                        _('Command') + ' ' + comm5 + ' ' + _('is processed'))
                    message = {
                        'Text': 'Command: ' + comm5 + ' was processed',
                        'SMSC': {
                            'Location': 1
                        },
                        'Number': m['Number'],
                    }
                    sm.SendSMS(message)
                    log.info(
                        NAME,
                        _('Command') + ': ' + comm5 + ' ' +
                        _('was processed and confirmation was sent as SMS to')
                        + ': ' + m['Number'])
                    sm.DeleteSMS(m['Folder'], m['Location'])
                    log.info(
                        NAME,
                        _('Received SMS was deleted and system is now poweroff'
                          ))
                    poweroff()  # poweroff linux system

                elif m['Text'] == comm6:  # If command = comm6 (update ospi system)
                    log.info(
                        NAME,
                        _('Command') + ' ' + comm6 + ' ' + _('is processed'))
                    message = {
                        'Text': 'Command: ' + comm6 + ' was processed',
                        'SMSC': {
                            'Location': 1
                        },
                        'Number': m['Number'],
                    }
                    sm.SendSMS(message)
                    log.info(
                        NAME,
                        _('Command') + ': ' + comm6 + ' ' +
                        _('was processed and confirmation was sent as SMS to')
                        + ': ' + m['Number'])
                    try:
                        from plugins.system_update import perform_update

                        perform_update()
                        log.info(
                            NAME,
                            _('Received SMS was deleted, update was performed and program will restart'
                              ))
                    except ImportError:
                        log.info(
                            NAME,
                            _('Received SMS was deleted, but could not perform update'
                              ))

                    sm.DeleteSMS(m['Folder'], m['Location'])

                elif m['Text'] == comm7:  # If command = comm7 (send email with foto from webcam)
                    log.info(
                        NAME,
                        _('Command') + ' ' + comm7 + ' ' + _('is processed'))
                    message = {
                        'Text': 'Command: ' + comm7 + ' was processed',
                        'SMSC': {
                            'Location': 1
                        },
                        'Number': m['Number'],
                    }
                    sm.SendSMS(message)
                    log.info(
                        NAME,
                        _('Command') + ': ' + comm7 + ' ' +
                        _('was processed and confirmation was sent as SMS to')
                        + ': ' + m['Number'])
                    try:
                        from plugins.webcam import get_run_cam, get_image_location

                        get_run_cam()  # process save foto to ./data/image.jpg
                        msg = _('SMS plug-in send image file from webcam.')

                        send_email(msg, attach=get_image_location())

                    except ImportError:
                        log.info(
                            NAME,
                            _('Received SMS was deleted, but could not send email with photo from webcam'
                              ))
                        message = {
                            'Text': 'Error: not send foto from webcam',
                            'SMSC': {
                                'Location': 1
                            },
                            'Number': m['Number'],
                        }
                        sm.SendSMS(message)
                    sm.DeleteSMS(m['Folder'], m['Location'])

                elif m['Text'] == comm8:  # If command = comm8 (send SMS with available commands)
                    log.info(
                        NAME,
                        _('Command') + ' ' + comm8 + ' ' + _('is processed'))
                    message = {
                        'Text':
                        'Available commands: ' + comm1 + ',' + comm2 + ',' +
                        comm3 + ',' + comm4 + ',' + comm5 + ',' + comm6 + ',' +
                        comm7 + ',' + comm8 + ',' + comm9 + 'xx',
                        'SMSC': {
                            'Location': 1
                        },
                        'Number':
                        m['Number'],
                    }
                    sm.SendSMS(message)
                    log.info(
                        NAME,
                        _('Command') + ': ' + comm8 + ' ' +
                        _('was processed and confirmation was sent as SMS to')
                        + ': ' + m['Number'])
                    sm.DeleteSMS(m['Folder'], m['Location'])
                    log.info(NAME, _('Received SMS was deleted'))

                elif m['Text'][0:len(
                        comm9
                )] == comm9:  # If command = lenght char comm9 (run now program xx)
                    num = m['Text'][len(
                        comm9
                    ):]  # number from sms text example: run36 -> num=36
                    log.info(
                        NAME,
                        _('Command') + ' ' + comm9 + ' ' + _('is processed'))
                    index = int(num)
                    if index <= programs.count(
                    ):  # if program number from sms text exists in program db
                        log.finish_run(None)
                        stations.clear()
                        prog = int(index - 1)
                        programs.run_now(prog)
                        log.info(
                            NAME,
                            _('Program') + ': ' + str(index) + ' ' +
                            _('now run'))
                        message = {
                            'Text': 'Program: ' + str(index) + ' now run',
                            'SMSC': {
                                'Location': 1
                            },
                            'Number': m['Number'],
                        }
                    else:
                        message = {
                            'Text': 'Program: ' + str(index) + ' no exists!',
                            'SMSC': {
                                'Location': 1
                            },
                            'Number': m['Number'],
                        }

                    sm.SendSMS(message)
                    log.info(
                        NAME,
                        _('Command') + ': ' + str(m['Text']) + ' ' +
                        _('was processed and confirmation was sent as SMS to')
                        + ': ' + m['Number'])
                    sm.DeleteSMS(m['Folder'], m['Location'])
                    log.info(NAME, _('Received SMS was deleted'))

                else:  # If SMS command is not defined
                    sm.DeleteSMS(m['Folder'], m['Location'])
                    log.info(
                        NAME,
                        _('Received command') + ' ' + m['Text'] + ' ' +
                        _('is not defined!'))

            else:  # If SMS was read
                sm.DeleteSMS(m['Folder'], m['Location'])
                log.info(NAME, _('Received SMS was deleted - SMS was read'))
        else:  # If telephone number is not admin 1 or admin 2 phone number
            sm.DeleteSMS(m['Folder'], m['Location'])
            log.info(NAME,
                     _('Received SMS was deleted - SMS was not from admin'))
Esempio n. 20
0
def sms_check(self):
    """Control and processing SMS"""
    data = get_sms_options()  # Load data from json file
    tel1 = data['tel1']
    tel2 = data['tel2']
    comm1 = data['txt1']
    comm2 = data['txt2']
    comm3 = data['txt3']
    comm4 = data['txt4']
    comm5 = data['txt5']
    comm6 = data['txt6']

    sm = gammu.StateMachine()
    sm.ReadConfig()
    try:
        sm.Init()
        print "Checking SMS..."
    except:
        print "Error: SMS modem fault"

    status = sm.GetSMSStatus()
    remain = status['SIMUsed'] + status['PhoneUsed'] + status['TemplatesUsed']
    sms = []
    start = True
    while remain > 0:
        if start:
            cursms = sm.GetNextSMS(Start=True, Folder=0)
            start = False
        else:
            cursms = sm.GetNextSMS(Location=cursms[0]['Location'], Folder=0)
        remain = remain - len(cursms)
        sms.append(cursms)
    data = gammu.LinkSMS(sms)
    for x in data:
        v = gammu.DecodeSMS(x)
        m = x[0]
        print '%-15s: %s' % ('Sender', m['Number'])
        print '%-15s: %s' % ('Date', str(m['DateTime']))
        print '%-15s: %s' % ('State', m['State'])
        print '%-15s: %s' % ('SMS command', m['Text'])
        if (m['Number']
                == tel1) or (m['Number']
                             == tel2):  # If telephone is admin 1 or admin 2
            self.add_status(
                time.strftime("%d.%m.%Y at %H:%M:%S",
                              time.localtime(time.time())) + ' SMS from admin')
            if m['State'] == "UnRead":  # If SMS is unread
                if m['Text'] == comm1:  # If command = comm1 (info - send SMS to admin phone1 and phone2)
                    self.add_status('Command ' + comm1 + ' is processed')
                    if gv.lrun[1] == 98:
                        pgr = 'Run-once'
                    elif gv.lrun[1] == 99:
                        pgr = 'Manual'
                    else:
                        pgr = str(gv.lrun[1])
                    start = time.gmtime(gv.now - gv.lrun[2])
                    if pgr != '0':
                        logline = ' {program: ' + pgr + ',station: ' + str(
                            gv.lrun[0]) + ',duration: ' + timestr(
                                gv.lrun[2]) + ',start: ' + time.strftime(
                                    "%H:%M:%S - %Y-%m-%d", start) + '}'
                    else:
                        logline = ' Last program none'
                    revision = ' Rev: ' + gv.ver_date
                    datastr = ('On ' + time.strftime(
                        "%d.%m.%Y at %H:%M:%S", time.localtime(time.time())) +
                               '. Run time: ' + uptime() + ' IP: ' + get_ip() +
                               logline + revision)
                    message = {
                        'Text': datastr,
                        'SMSC': {
                            'Location': 1
                        },
                        'Number': m['Number'],
                    }
                    sm.SendSMS(message)
                    self.add_status(
                        'Command: ' + comm1 +
                        ' was processed and confirmation was sent as SMS to: '
                        + m['Number'])
                    self.add_status('SMS text: ' + datastr)

                    sm.DeleteSMS(m['Folder'], m['Location'])  # SMS deleted
                    self.add_status('Received SMS was deleted')

                elif m['Text'] == comm2:  # If command = comm2 (stop - system OSPi off)
                    self.add_status('Command ' + comm2 + ' is processed')
                    gv.sd['en'] = 0  # disable system OSPi
                    jsave(gv.sd, 'sd')  # save en = 0
                    message = {
                        'Text': 'Command: ' + comm2 + ' was processed',
                        'SMSC': {
                            'Location': 1
                        },
                        'Number': m['Number'],
                    }
                    sm.SendSMS(message)
                    self.add_status(
                        'Command: ' + comm2 +
                        ' was processed and confirmation was sent as SMS to: '
                        + m['Number'])
                    sm.DeleteSMS(m['Folder'], m['Location'])
                    self.add_status('Received SMS was deleted')

                elif m['Text'] == comm3:  # If command = comm3 (start - system ospi on)
                    self.add_status('Command ' + comm3 + ' is processed')
                    gv.sd['en'] = 1  # enable system OSPi
                    jsave(gv.sd, 'sd')  # save en = 1
                    message = {
                        'Text': 'Command: ' + comm3 + ' was processed',
                        'SMSC': {
                            'Location': 1
                        },
                        'Number': m['Number'],
                    }
                    sm.SendSMS(message)
                    self.add_status(
                        'Command: ' + comm3 +
                        ' was processed and confirmation was sent as SMS to: '
                        + m['Number'])
                    sm.DeleteSMS(m['Folder'], m['Location'])
                    self.add_status('Received SMS was deleted')

                elif m['Text'] == comm4:  # If command = comm4 (reboot system)
                    self.add_status('Command ' + comm4 + ' is processed')
                    message = {
                        'Text': 'Command: ' + comm4 + ' was processed',
                        'SMSC': {
                            'Location': 1
                        },
                        'Number': m['Number'],
                    }
                    sm.SendSMS(message)
                    self.add_status(
                        'Command: ' + comm4 +
                        ' was processed and confirmation was sent as SMS to: '
                        + m['Number'])
                    sm.DeleteSMS(m['Folder'], m['Location'])
                    self.add_status(
                        'Received SMS was deleted and system is now reboot')
                    self._sleep(10)
                    reboot()  # restart linux system

                elif m['Text'] == comm5:  # If command = comm5 (poweroff system)
                    self.add_status('Command ' + comm5 + ' is processed')
                    message = {
                        'Text': 'Command: ' + comm5 + ' was processed',
                        'SMSC': {
                            'Location': 1
                        },
                        'Number': m['Number'],
                    }
                    sm.SendSMS(message)
                    self.add_status(
                        'Command: ' + comm5 +
                        ' was processed and confirmation was sent as SMS to: '
                        + m['Number'])
                    sm.DeleteSMS(m['Folder'], m['Location'])
                    self.add_status(
                        'Received SMS was deleted and system is now poweroff')
                    self._sleep(10)
                    poweroff()  # poweroff linux system

                elif m['Text'] == comm6:  # If command = comm6 (update ospi system)
                    self.add_status('Command ' + comm6 + ' is processed')
                    message = {
                        'Text': 'Command: ' + comm6 + ' was processed',
                        'SMSC': {
                            'Location': 1
                        },
                        'Number': m['Number'],
                    }
                    sm.SendSMS(message)
                    self.add_status(
                        'Command: ' + comm6 +
                        ' was processed and confirmation was sent as SMS to: '
                        + m['Number'])
                    try:
                        from plugins.system_update import perform_update

                        perform_update()
                        self.add_status(
                            'Received SMS was deleted, update was performed and program will restart'
                        )
                    except ImportError:
                        self.add_status(
                            'Received SMS was deleted, but could not perform update'
                        )

                    sm.DeleteSMS(m['Folder'], m['Location'])

                else:  # If SMS command is not defined
                    sm.DeleteSMS(m['Folder'], m['Location'])
                    self.add_status('Received command ' + m['Text'] +
                                    ' is not defined!')

            else:  # If SMS was read
                sm.DeleteSMS(m['Folder'], m['Location'])
                self.add_status('Received SMS was deleted - SMS was read')
        else:  # If telephone number is not admin 1 or admin 2 phone number
            sm.DeleteSMS(m['Folder'], m['Location'])
            self.add_status(
                'Received SMS was deleted - SMS was not from admin')
Esempio n. 21
0
    while remain > 0:
        if start:
            cursms = state_machine.GetNextSMS(Start=True, Folder=0)
            start = False
        else:
            cursms = state_machine.GetNextSMS(
                Location=cursms[0]['Location'], Folder=0
            )
        remain = remain - len(cursms)
        sms.append(cursms)
except gammu.ERR_EMPTY:
    # This error is raised when we've reached last entry
    # It can happen when reported status does not match real counts
    print('Failed to read all messages!')

data = gammu.LinkSMS(sms)

for x in data:
    v = gammu.DecodeSMS(x)

    m = x[0]
    print()
    print('{0:<15}: {1}'.format('Number', m['Number']))
    print('{0:<15}: {1}'.format('Date', str(m['DateTime'])))
    print('{0:<15}: {1}'.format('State', m['State']))
    print('{0:<15}: {1}'.format('Folder', m['Folder']))
    print('{0:<15}: {1}'.format('Validity', m['SMSC']['Validity']))
    loc = []
    for m in x:
        loc.append(str(m['Location']))
    print('{0:<15}: {1}'.format('Location(s)', ', '.join(loc)))
Esempio n. 22
0
#!/usr/bin/env python

# Simple test for testing SMS decoding/encoding with linking
# (linking is not really needed here)

import gammu

# text of sms
txt = '.........1.........2.........3.........4.........5.........6.........7.........8.........9........0.........1.........2.........3.........4.........5.........6.........7.........8.........9........0.........1.........2.........3.........4.........5.........6.........7.........8.........9........0'

# SMS info about message
smsinfo = {'Entries': [{'ID': 'ConcatenatedTextLong', 'Buffer': txt}]}

# encode SMS
sms = gammu.EncodeSMS(smsinfo)

# link SMS
linked = gammu.LinkSMS([[sms[0]], [sms[1]]], True)

# decode back SMS
decodedsms = gammu.DecodeSMS(linked[0])

# show results
print "Text:", decodedsms['Entries'][0]['Buffer']
print "Comparsion:", (decodedsms['Entries'][0]['Buffer'] == txt)
Esempio n. 23
0
    sys.exit(1)

#sm = gammu.StateMachine()
#sm.ReadConfig()
#sm.Init()

charsetencoder = codecs.getencoder(sys.getdefaultencoding())

filename = sys.argv[1]

backup = gammu.ReadSMSBackup(filename)

# Make nested array
list = [[x] for x in backup]

data = gammu.LinkSMS(list)

for x in data:
    v = gammu.DecodeSMS(x)

    m = x[0]
    print
    print '%-15s: %s' % ('Number', m['Number'])
    print '%-15s: %s' % ('Date', str(m['DateTime']))
    print '%-15s: %s' % ('State', m['State'])
    print '%-15s: %s' % ('Folder', m['Folder'])
    print '%-15s: %s' % ('Validity', m['SMSC']['Validity'])
    loc = []
    for m in x:
        loc.append(str(m['Location']))
    print '%-15s: %s' % ('Location(s)', ', '.join(loc))
Esempio n. 24
0
def sms_check(self):
    """Control and processing SMS"""
    data = get_sms_options()  # Load data from json file
    tel1 = data["tel1"]
    tel2 = data["tel2"]
    comm1 = data["txt1"]
    comm2 = data["txt2"]
    comm3 = data["txt3"]
    comm4 = data["txt4"]
    comm5 = data["txt5"]
    comm6 = data["txt6"]

    sm = gammu.StateMachine()
    sm.ReadConfig()
    try:
        sm.Init()
        print("Checking SMS...")
    except:
        print("Error: SMS modem fault")

    status = sm.GetSMSStatus()
    remain = status["SIMUsed"] + status["PhoneUsed"] + status["TemplatesUsed"]
    sms = []
    start = True
    while remain > 0:
        if start:
            cursms = sm.GetNextSMS(Start=True, Folder=0)
            start = False
        else:
            cursms = sm.GetNextSMS(Location=cursms[0]["Location"], Folder=0)
        remain = remain - len(cursms)
        sms.append(cursms)
    data = gammu.LinkSMS(sms)
    for x in data:
        v = gammu.DecodeSMS(x)
        m = x[0]
        print("%-15s: %s" % ("Sender", m["Number"]))
        print("%-15s: %s" % ("Date", str(m["DateTime"])))
        print("%-15s: %s" % ("State", m["State"]))
        print("%-15s: %s" % ("SMS command", m["Text"]))
        if (m["Number"]
                == tel1) or (m["Number"]
                             == tel2):  # If telephone is admin 1 or admin 2
            self.add_status(
                time.strftime("%d.%m.%Y at %H:%M:%S",
                              time.localtime(time.time())) + " SMS from admin")
            if m["State"] == "UnRead":  # If SMS is unread
                if (
                        m["Text"] == comm1
                ):  # If command = comm1 (info - send SMS to admin phone1 and phone2)
                    self.add_status("Command " + comm1 + " is processed")
                    if gv.lrun[1] == 98:
                        pgr = "Run-once"
                    elif gv.lrun[1] == 99:
                        pgr = "Manual"
                    else:
                        pgr = str(gv.lrun[1])
                    start = time.gmtime(gv.now - gv.lrun[2])
                    if pgr != "0":
                        logline = (
                            " {program: " + pgr + ",station: " +
                            str(gv.lrun[0]) + ",duration: " +
                            timestr(gv.lrun[2]) + ",start: " +
                            time.strftime("%H:%M:%S - %Y-%m-%d", start) + "}")
                    else:
                        logline = " Last program none"
                    revision = " Rev: " + gv.ver_date
                    datastr = ("On " + time.strftime(
                        "%d.%m.%Y at %H:%M:%S", time.localtime(time.time())) +
                               ". Run time: " + uptime() + " IP: " + get_ip() +
                               logline + revision)
                    message = {
                        "Text": datastr,
                        "SMSC": {
                            "Location": 1
                        },
                        "Number": m["Number"],
                    }
                    sm.SendSMS(message)
                    self.add_status(
                        "Command: " + comm1 +
                        " was processed and confirmation was sent as SMS to: "
                        + m["Number"])
                    self.add_status("SMS text: " + datastr)

                    sm.DeleteSMS(m["Folder"], m["Location"])  # SMS deleted
                    self.add_status("Received SMS was deleted")

                elif m["Text"] == comm2:  # If command = comm2 (stop - system SIP off)
                    self.add_status("Command " + comm2 + " is processed")
                    gv.sd["en"] = 0  # disable system SIP
                    jsave(gv.sd, "sd")  # save en = 0
                    message = {
                        "Text": "Command: " + comm2 + " was processed",
                        "SMSC": {
                            "Location": 1
                        },
                        "Number": m["Number"],
                    }
                    sm.SendSMS(message)
                    self.add_status(
                        "Command: " + comm2 +
                        " was processed and confirmation was sent as SMS to: "
                        + m["Number"])
                    sm.DeleteSMS(m["Folder"], m["Location"])
                    self.add_status("Received SMS was deleted")

                elif m["Text"] == comm3:  # If command = comm3 (start - system SIP on)
                    self.add_status("Command " + comm3 + " is processed")
                    gv.sd["en"] = 1  # enable system SIP
                    jsave(gv.sd, "sd")  # save en = 1
                    message = {
                        "Text": "Command: " + comm3 + " was processed",
                        "SMSC": {
                            "Location": 1
                        },
                        "Number": m["Number"],
                    }
                    sm.SendSMS(message)
                    self.add_status(
                        "Command: " + comm3 +
                        " was processed and confirmation was sent as SMS to: "
                        + m["Number"])
                    sm.DeleteSMS(m["Folder"], m["Location"])
                    self.add_status("Received SMS was deleted")

                elif m["Text"] == comm4:  # If command = comm4 (reboot system)
                    self.add_status("Command " + comm4 + " is processed")
                    message = {
                        "Text": "Command: " + comm4 + " was processed",
                        "SMSC": {
                            "Location": 1
                        },
                        "Number": m["Number"],
                    }
                    sm.SendSMS(message)
                    self.add_status(
                        "Command: " + comm4 +
                        " was processed and confirmation was sent as SMS to: "
                        + m["Number"])
                    sm.DeleteSMS(m["Folder"], m["Location"])
                    self.add_status(
                        "Received SMS was deleted and system is now reboot")
                    self._sleep(10)
                    reboot()  # restart linux system

                elif m["Text"] == comm5:  # If command = comm5 (poweroff system)
                    self.add_status("Command " + comm5 + " is processed")
                    message = {
                        "Text": "Command: " + comm5 + " was processed",
                        "SMSC": {
                            "Location": 1
                        },
                        "Number": m["Number"],
                    }
                    sm.SendSMS(message)
                    self.add_status(
                        "Command: " + comm5 +
                        " was processed and confirmation was sent as SMS to: "
                        + m["Number"])
                    sm.DeleteSMS(m["Folder"], m["Location"])
                    self.add_status(
                        "Received SMS was deleted and system is now poweroff")
                    self._sleep(10)
                    poweroff()  # poweroff linux system

                elif m["Text"] == comm6:  # If command = comm6 (update SIP system)
                    self.add_status("Command " + comm6 + " is processed")
                    message = {
                        "Text": "Command: " + comm6 + " was processed",
                        "SMSC": {
                            "Location": 1
                        },
                        "Number": m["Number"],
                    }
                    sm.SendSMS(message)
                    self.add_status(
                        "Command: " + comm6 +
                        " was processed and confirmation was sent as SMS to: "
                        + m["Number"])
                    try:
                        from plugins.system_update import perform_update

                        perform_update()
                        self.add_status(
                            "Received SMS was deleted, update was performed and program will restart"
                        )
                    except ImportError:
                        self.add_status(
                            "Received SMS was deleted, but could not perform update"
                        )

                    sm.DeleteSMS(m["Folder"], m["Location"])

                else:  # If SMS command is not defined
                    sm.DeleteSMS(m["Folder"], m["Location"])
                    self.add_status("Received command " + m["Text"] +
                                    " is not defined!")

            else:  # If SMS was read
                sm.DeleteSMS(m["Folder"], m["Location"])
                self.add_status("Received SMS was deleted - SMS was read")
        else:  # If telephone number is not admin 1 or admin 2 phone number
            sm.DeleteSMS(m["Folder"], m["Location"])
            self.add_status(
                "Received SMS was deleted - SMS was not from admin")
Esempio n. 25
0
    def retrieveEvent(self) -> Optional[SourceEvent]:
        if self.__gsm is None:
            return None
        if self.parser is None:
            return None

        start = True
        cursms = None
        sms = []

        # self.dbgPrint("Searching for new SMS")

        status = self.__gsm.GetSMSStatus()

        remain = status['SIMUsed'] + status['PhoneUsed'] + status[
            'TemplatesUsed']

        try:
            while remain > 0:
                if start:
                    cursms = self.__gsm.GetNextSMS(Start=True, Folder=0)
                    start = False
                elif cursms is not None:
                    cursms = self.__gsm.GetNextSMS(
                        Location=cursms[0]['Location'], Folder=0)  #pylint: disable=unsubscriptable-object
                else:
                    self.error("Failed to read further messages")
                    break
                remain = remain - len(cursms)
                sms.append(cursms)
        except gammu.ERR_EMPTY:
            # This error is raised when we've reached last entry
            # It can happen when reported status does not match real counts
            self.error("Failed to read all messages")

        # while True:
        #     try:
        #         if start:
        #             cursms = self.__gsm.GetNextSMS(Start = True, Folder = 0)
        #             start = False
        #         else:
        #             cursms = self.__gsm.GetNextSMS(Location = cursms[0]['Location'], Folder = 0)
        #
        #         sms.append(cursms)
        #     except gammu.ERR_EMPTY:
        #         break

        if start:
            return None

        data = gammu.LinkSMS(sms)

        rawText = ""
        sender = ""
        timeStamp = ""
        foundMessage = False
        locs = []

        for x in data:
            v = gammu.DecodeSMS(x)

            m = x[0]

            # all parts of multipart SMS received ?
            if m['UDH']['AllParts'] > len(x):
                continue

            timeStamp = str(m['DateTime'])
            sender = m['Number']

            for m in x:
                locs.append(m['Location'])

            if v is None:
                rawText += m['Text']  # .encode('utf-8')
            else:
                for e in v['Entries']:
                    if e['Buffer'] is not None:
                        rawText += e['Buffer']  # .encode('utf-8')

            foundMessage = True
            break

        if not foundMessage:
            return None

        for loc in locs:
            self.__gsm.DeleteSMS(Location=loc, Folder=0)

        self.clrPrint("Received message")

        self.dbgPrint("Received SMS from " + sender + " (timestamp " +
                      timeStamp + ")")
        self.dbgPrint(rawText)

        sourceEvent = SourceEvent()
        sourceEvent.source = SourceEvent.SOURCE_SMS
        sourceEvent.timestamp = timeStamp
        sourceEvent.sender = sender
        sourceEvent.raw = rawText

        if not SourceDriver.isSenderAllowed(allowlist=self.__allowlist,
                                            denylist=self.__denylist,
                                            sender=sender):
            self.error("Received unhandled message (ignored sender)")
            return UnhandledEvent.fromSourceEvent(
                sourceEvent, UnhandledEvent.CAUSE_IGNORED_SENDER)

        parsedSourceEvent = self.parser.parseMessage(sourceEvent,
                                                     self.__lastEvent)

        if parsedSourceEvent is not None:
            self.__lastEvent = parsedSourceEvent

        return parsedSourceEvent