Ejemplo n.º 1
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')
Ejemplo n.º 2
0
def sms_check(self):
    """Control and processing SMS"""
    data = get_sms_options()  # Load data from json file
    tels = data['tels']
    comm1 = data['txt1']
    comm2 = data['txt2']
    comm3 = data['txt3']
    comm4 = data['txt4']
    comm5 = data['txt5']
    comm6 = data['txt6']
    comm7 = data['txt7']

    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'] in tels:  # If telephone in admin lists
            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'].upper().strip() == comm1.upper():           # If command = comm1 (info - send SMS to admin phone1 and phone2)
                    self.add_status('Command ' + comm1 + ' is processed')
                    # Current Status
                    logline = "Status: "
                    if gv.srvals == [0] * len(gv.srvals):
                        logline += "Idle. "
                    elif gv.sd['mm'] == 1: # manual mode
                        logline += "Manual Mode."
                        for sid in range(len(gv.srvals)):
                            if gv.srvals[sid]:
                                if gv.rs[sid][1] == float('inf'):
                                    end_time = 'inf'
                                else:
                                    end_time = time.strftime('%m-%d %H:%M', time.gmtime(gv.rs[sid][1]))
                                logline += '\n st: ' + str(sid + 1) + ' dur: ' + end_time
                        logline += "\n"
                    else:
                        logline += "Auto Mode."
                        for sid in range(len(gv.srvals)):
                            if gv.srvals[sid]:
                                if gv.rs[sid][1] == float('inf'):
                                    end_time = 'inf'
                                else:
                                    end_time = time.strftime('%m-%d %H:%M', time.gmtime(gv.rs[sid][1]))
                                logline += '\n st: ' + str(sid + 1 ) + ' dur: ' + end_time
                        logline += "\n"

                    # Last RUN
                    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 += 'Last RUN: { prg: ' + pgr + ',st: ' + str(gv.lrun[0]) + ',dur: ' + timestr(
                            gv.lrun[2]) + ',start: ' + time.strftime("%H:%M - %m-%d", start) + '}'
                    else:
                        logline += ' Last program none'
               #     revision = ' Rev: ' + gv.ver_date
                    datastr = ('On ' + time.strftime("%d.%m.%Y at %H:%M", time.localtime(
                        time.time())) + '. ' + logline)


                    msgs=[""]
                    idx = 0
                    for line in datastr.splitlines():
                        if (len(msgs[idx]) + len(line)) < 140:
                            msgs[idx] += line + "\n"
                        else:
                            msgs[idx] += "{continues....}"
                            idx += 1
                            msgs.append(line)

                    for txt in msgs:
                        message = {
                            'Text': txt,
                            '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')

                    self.add_status('Command ' + comm2 + ' is processed')
                    stop_stations()
                    time.sleep(3)
                    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'].upper().strip() == comm3.upper():         # If command = comm3 (start - system sip on)
                    self.add_status('Command ' + comm3 + ' is processed')
                    gv.sd['en'] = 1             # enable system SIP
                    stop_stations()
                    gv.sd['mm'] = 0             # Put in auto mode
                    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'].upper().strip() == comm4.upper():        # 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'].upper().strip() == comm5.upper():        # 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'].upper().strip() == comm6.upper():        # 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'])

                elif m['Text'].strip().split()[0].upper() == comm7.upper():        # If command = comm7 (manual mode)
                    self.add_status('Command ' + comm7 + ' is processed')
                    message = ""
                    command = m['Text'].strip().split()[1].upper()

                    if (gv.sd['en'] == 0 or gv.sd['mm'] == 0 )  and command != "ON":
                        message = {
                        'Text': 'Command: ' + comm7 + ' cannot continue, enable manual mode first with: ' +comm7+ ' on',
                        'SMSC': {'Location': 1},
                        'Number': m['Number'],
                        }

                    elif  command == "ON": # enable manual mode
                        stop_stations()
                        gv.sd['en'] = 1
                        gv.sd['mm'] = 1
                        jsave(gv.sd, 'sd')
                        message = {
                        'Text': 'Command: ' + comm7 + '  manual mode enabled',
                        'SMSC': {'Location': 1},
                        'Number': m['Number'],
                        }
                    else :
                        # check the correct formatting
                        # should be a pair of int separated by comma
                        stations_duration = [0] * len(gv.srvals)
                        try:
                            for c in m['Text'].split()[1:]:
                                station,duration = c.split(',')
                                if not (0 < (int(station) -1) < len(stations_duration)): # out of range
                                    raise ValueError("Out of Range station ID")
                                stations_duration[int(station) - 1 ] = int(duration)*60
                        except ValueError:
                            message = {
                            'Text': 'Command: ' + comm7 + ' cannot continue, wrong command formatting, should be '
                                                          'station,duration (in minutes)\n Example: ' + comm7 + ' 2,10 3,10',
                            'SMSC': {'Location': 1},
                            'Number': m['Number'],
                            }
                            self.add_status('Command ' + comm7 + ' has formatting errors')

                        if message == "":
                            # logic copied from webpages.get_set_station
                            for sid in range(len(stations_duration)):
                                print "sid: " +  str(sid)
                                if sid == gv.sd['mas'] - 1:
                                    continue
                                duration = stations_duration[sid]
                                print "duration: " + str(duration)
                                if duration > 0:
                                    gv.rs[sid][0] = gv.now  # set start time to current time
                                    gv.rs[sid][2] = duration
                                    gv.rs[sid][1] = gv.rs[sid][0] + duration  # stop time = start time + duration
                                    gv.rs[sid][3] = 99  # set program index
                                    gv.ps[sid][1] = duration
                                    gv.sd['bsy'] = 1
                                elif duration <= 0 and gv.srvals[sid]: # we should stop the running station
                                    gv.rs[sid][1] = gv.now
                                time.sleep(1)


                            message = {
                            'Text': 'Command: ' + comm7 + ' Processed OK ',
                            'SMSC': {'Location': 1},
                            'Number': m['Number'],
                            }
                            self.add_status('Command ' + comm7 + ' Command OK')

                    sm.SendSMS(message)
                    self.add_status(
                        'Command: ' + comm7 + ' was processed and confirmation was sent as SMS to: ' + m['Number'])
                    sm.DeleteSMS(m['Folder'], m['Location'])
                    self.add_status('Received SMS was deleted')
                    self._sleep(10)


                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')
Ejemplo n.º 3
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')
Ejemplo n.º 4
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")
Ejemplo n.º 5
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'))