Beispiel #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')
Beispiel #2
0
    def GET(self):
        qdict = web.input()
        try:
            ddict = json.loads(qdict['data'])
        except:
            raise web.unauthorized()

        force_reboot = False
        info = {}
        for l in ['wlog', 'elog', 'slog', 'evlog']:
            if l in ddict and ddict[l]:
                end = ddict['end_date']
                days = ddict['days_before']
                start_after = ddict['start_after']
                prefix = ''
                try:
                    if l in ['slog', 'evlog']:
                        prefix = 'sensors/' + gv.plugin_data['ld'][int(ddict['ldi'])]['name'] + '/logs/'
                except:
                    pass
                records = read_log(prefix+l, end, days, start_after)
                info[l] = records

        for dlog in ['dlogirricloud', 'dlogirricloud_monitor', 'dlogirricloud_net_config']:
            if dlog in ddict and ddict[dlog]:
                records = []
                try:
                    with gv.log_lock:
                        with open('./logs/' + dlog[4:] + '.out', 'r') as file:
                            records = file.readlines()
                except:
                    pass
                info[dlog] = []
                for r in records:
                    info[dlog].append(r)

        if 'lrun' in ddict and ddict['lrun']:
            info['lrun'] = gv.lrun

        if 'programs' in ddict:
            if ddict['programs'] == 1:
                info['programs'] = gv.pd
            else:
                gv.pd = ddict['programs']
                jsave(gv.pd, 'programs')
                info['programs'] = 1

        if 'ps' in ddict and ddict['ps']:
            info['ps'] = gv.ps

        if 'sbits' in ddict and ddict['sbits']:
            info['sbits'] = gv.sbits

        if 'srvals' in ddict and ddict['srvals']:
            info['srvals'] = gv.srvals

        if 'sensors' in ddict and 'ld' in gv.plugin_data:
            if ddict['sensors'] == 1:
                info['sensors'] = []
                try:
                    if 'ldi' not in ddict or int(ddict['ldi']) == -1:
                        info['sensors'] = gv.plugin_data['ld']
                    else:
                        info['sensors'] = gv.plugin_data['ld'][int(ddict['ldi'])]
                except:
                    pass
                info['sensboards'] = i2c.get_vsb_boards().keys()
                info['remotesensboards'] = get_remote_sensor_boards()
            else:
                try:
                    if 'ldi' not in ddict or int(ddict['ldi']) == -1:
                        gv.plugin_data['ld'] = ddict['sensors']
                    else:
                        gv.plugin_data['ld'][int(ddict['ldi'])] = ddict['sensors']
                except:
                    gv.plugin_data['ld'] = ddict['sensors']
                jsave(gv.plugin_data['ld'], 'sensors')
                info['sensors'] = 1

        if 'camera' in ddict and 'ca' in gv.plugin_data:
            if ddict['camera'] == 1:
                info['camera'] = gv.plugin_data['ca']
                if 'cai' in ddict and ddict['cai']:
                    info['cai'] = ''
                    if gv.plugin_data['ca']['enable_camera'] == 'on':
                        try:
                            with open('./static/images/camera.jpg', mode='rb') as file: # b is important -> binary
                                info['cai'] = base64.b64encode(file.read())
                        except:
                            pass
            else:
                gv.plugin_data['ca'] = ddict['camera']
                jsave(gv.plugin_data['ca'], 'camera')
                info['camera'] = 1

        if 'sd' in ddict:
            if ddict['sd'] == 1:
                sd = gv.sd.copy()
                del sd['substation_network']
                del sd['salt']
                del sd['password']
                del sd['pwd']
                del sd['enable_upnp'] # stuff from base configuration stays as was
                del sd['subnet_only_substations']
                del sd['external_proxy_port']
                kill_keys = []
                for k,v in sd.iteritems():
                    if len(k) > 2 and (k[0:2] == 'te' or k[0:2] == 'et'):
                        kill_keys.append(k)
                for k in kill_keys:
                    del sd[k] # dont send textemail or et_weather stuff
                info['sd'] = sd
            else:
                for field in ddict['sd']:
                    gv.sd[field] = ddict['sd'][field]
                update_hostname(gv.sd['name'])
                update_tza(gv.sd['tza'])
                jsave(gv.sd, 'sd')
                info['sd'] = 1
                force_reboot = True

        if 'snames' in ddict:
            if ddict['snames'] == 1:
                info['snames'] = gv.snames
            else:
                gv.snames = ddict['snames']
                jsave(gv.snames, 'snames')
                info['snames'] = 1

        if 'snotes' in ddict:
            if ddict['snotes'] == 1:
                info['snotes'] = gv.snotes
            else:
                gv.snotes = ddict['snotes']
                jsave(gv.snotes, 'snotes')
                info['snotes'] = 1

        if 'update_status' in ddict and ddict['update_status']:
            updatechecker.update_rev_data()
            info['update_status'] = updatechecker.status

        web.header('Content-Type', 'application/json')
        ret_str = json.dumps(info)
        if force_reboot:
            reboot(5)  # give a few seconds to reply
        return ret_str
Beispiel #3
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')
Beispiel #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")
Beispiel #5
0
    def run(self):
        if disable_substations:
            return        

        gv.logger.info('Substation plugin started')        
        time.sleep(7) # let things wake up, but keep less than delay for sending email

        last_message_base = gv.now - 60
        last_day = gv.now//86400 # wait at least a day before removing stale log files so startup does not delete them
        while True:
            try:
                cur_day = gv.now//86400
                if gv.sd['slave'] and gv.now - last_message_base >= 60:
                    try:
                        last_message_base = gv.now
                        data = message_base('suslj')
                        if 'unreachable' in data:
                            raise IOError, 'UnreachableMaster'
                        force_reboot = False
                        # update common data that has changed on the master
                        for grouping in data:
                            if gv.sd['master']:
                                continue
                            for key in data[grouping]:
                                if grouping == 'sd':
                                    if key in gv.sd:
                                        if gv.sd[key] != data['sd'][key]:
                                            gv.logger.info('Changing gv.sd[' + key + '] from ' + str(gv.sd[key]) + ' to ' + str(data['sd'][key]))
                                            if key == 'remote_support_port' and gv.sd['enable_upnp']:
                                                gv.logger.critical('substation_run: Unexpected key of remote_support_port')
                                                if gv.sd[key] != 0: # delete old
                                                    update_upnp(get_ip(), [gv.sd[key]])
                                                if data['sd'][key] != 0:
                                                    update_upnp(get_ip(), [], [[22, data['sd'][key]]])
                                            gv.sd[key] = data['sd'][key]
                                            if key == 'tza':
                                                with open('/etc/timezone','w') as file:
                                                    file.write(qdict['o'+f]+'\n')
                                                subprocess.call(['dpkg-reconfigure', '-f', 'non-interactive', 'tzdata'])
                                                force_reboot = True
                                            elif key == 'loc' or key == 'lang':
                                                force_reboot = True
                                    else:
                                        gv.logger.info('Setting gv.sd[' + key + '] to ' + str(data['sd'][key]))
                                        gv.sd[key] = data['sd'][key]
                                elif grouping in gv.plugin_data:
                                    if key in gv.plugin_data[grouping]:
                                        if gv.plugin_data[grouping][key] != data[grouping][key]:
                                            gv.logger.info('Changing gv.plugin_data[' + grouping +'][' + key + '] from ' + str(gv.plugin_data[grouping][key]) + ' to ' + str(data[grouping][key]))
                                            gv.plugin_data[grouping][key] = data[grouping][key]
                                    else:
                                        gv.logger.info('Setting gv.plugin_data[' + grouping +'][' + key + '] to ' + str(data[grouping][key]))
                                        gv.plugin_data[grouping][key] = data[grouping][key]
                                elif grouping == 'other':
                                    if key == 'websession':
                                        web.config._session.user = data[grouping][key]
                                    elif key == 'datetime':
                                        try:
                                            pass
#                                            subprocess.call(['date', '--set='+data[grouping][key]])
                                        except:
                                            gv.logger.exception('Could not set datetime to ' + data[grouping][key])
                            if grouping == 'sd':
                                jsave(gv.sd, 'sd')
                            elif grouping != 'other':
                                pass
                        if force_reboot:
                            reboot(5) # give a few seconds before reboot

                    except Exception as ex:
                        gv.logger.info('No master response.  ip: ' + get_ip_to_base() + \
                                       ' port: ' + str(gv.sd['master_port']) + \
                                       ' Exception: ' + str(ex))
                        try:
                            iwout = subprocess.check_output(['iwconfig', 'wlan0'])
                            lines = iwout.split('\n')
                            for l in lines:
                                if 'ESSID:' in l:
                                    gv.logger.info('slave iwconfig wlan0 ' + l[l.find('ESSID:'):])
                        except Exception as ex:
                            gv.logger.info('slave could not check iwconfig: ' + str(ex))

                if gv.sd['master']:
                    for subid in range(1,len(gv.plugin_data['su']['subinfo'])):
                        sub = gv.plugin_data['su']['subinfo'][subid]
                        try:
                            if sub['status'] != 'unreachable' and gv.now - sub['last_join'] >= 90: # if havent received join in a while reach out
                                qd = {'substation':subid}
                                load_and_save_remote(qd, [], 'susldr', 'data', {}) # touch a slave to ensure still alive
                        except Exception as ex:
                            gv.logger.info('substations reach out to slave: No response from slave: ' +
                                           sub['name'] + ' Exception: ' + str(ex))
                            sub['status'] = 'unreachable'
                            try:
                                iwout = subprocess.check_output(['iwconfig', 'wlan0'])
                                lines = iwout.split('\n')
                                for l in lines:
                                    if 'ESSID:' in l:
                                        gv.logger.info('master iwconfig wlan0 ' + l[l.find('ESSID:'):])
                            except Exception as ex:
                                gv.logger.info('master could not check iwconfig: ' + str(ex))

                    if cur_day != last_day:
                        last_day = cur_day
                        # delete any imported log files from substations that are no longer active
                        files = glob.glob('./data/imported_logs/*')
                        for full_name in files:
                            sub_name = full_name[full_name.rfind('/')+1:]
                            found_slave = 0
                            for subid in range(1,len(gv.plugin_data['su']['subinfo'])):
                                if sub_name == gv.plugin_data['su']['subinfo'][subid]['name']:
                                    found_slave = subid
                                    break
                            if found_slave == 0:
                                try:
                                    shutil.rmtree(full_name)
                                    gv.logger.info('removed substree: ' + full_name)
                                except Exception as ex:
                                    gv.logger.warning('failed to remove substree: ' + full_name + ' ex: ' + str(ex))

            except Exception as ex:
                self.start_status('', 'Substation encountered error: ' + str(ex))

            self._sleep(30)
Beispiel #6
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')
Beispiel #7
0
def check_factory_reset():
    """Check every five seconds to see if we need to do a factory reset"""

    while True:
        time.sleep(5)
        try:
            factory_reset = False
            i2c_reset = False
            try:
                # if factory_reset file is present or hw button is pushed.
                if pi.read(button_pin) == 0:
                    factory_reset = True
                    logger.warning('button factory reset')
                else:
                    try:
                        with open('data/factory_reset', 'r') as f:
                            factory_reset = True
                            logger.warning('file factory reset')
                        if factory_reset:
                            subprocess.call(['rm', 'data/factory_reset'])
                    except:
                        pass
            except Exception as ex:
                logger.warning('button read failure: ' + str(ex))

            print 'checking factory reset', factory_reset
            if factory_reset:
                # Factory reset request
                logger.warning('factory reset')
                light_vsb_boards()
                try:
                    type = ''
                    usbs = subprocess.check_output(['lsusb'])
                    usbl = usbs.split('\n')
                    for usb in usbl:
                        if 'Ralink Technology' in usb:
                            type = 'CanaKit' if type == '' else 'Unknown'
                        elif 'Realtek Semiconductor' in usb:
                            type = 'TP' if type == '' else 'Unknown'

                    if type != '' and type != 'Unknown':
                        for file in [
                                '/etc/hostapd/hostapd.conf',
                                '/usr/sbin/hostapd',
                                '/etc/wpa_supplicant/functions.sh'
                        ]:
                            rc = subprocess.call(
                                ['diff', file, file + '-' + type])
                            if rc == 0:
                                logger.debug(file + ' and ' + file + '-' +
                                             type + ' match')
                            else:
                                logger.critical('Rebinding ' + file +
                                                ' to match ' + file + '-' +
                                                type)
                                subprocess.call(['rm', file])
                                subprocess.call(
                                    ['ln', '-s', file + '-' + type, file])
                    else:
                        logger.info(
                            'leaving hostapd and wpa_supplicant unchanged.  type: '
                            + type)

                except Exception as ex:
                    logger.exception(
                        'Could not validate/change hostapd and wpa_supplicant usage: '
                        + str(ex))
                logger.info(
                    'restoring orig /etc/network/interfaces and /etc/wpa_supplicant/wpa_supplicant.conf'
                )
                shutil.copy2('/etc/network/interfaces.orig',
                             '/etc/network/interfaces')
                shutil.copy2('/etc/wpa_supplicant/wpa_supplicant.conf.orig',
                             '/etc/wpa_supplicant/wpa_supplicant.conf')
                shutil.copy2('/etc/dhcpcd.conf.orig', '/etc/dhcpcd.conf')
                logger.info('starting sip_net_start')
                rc = subprocess.call(
                    ['/usr/bin/python',
                     '/home/pi/Irricloud/sip_net_start.py'])  # leads to reboot
                logger.debug('sip_net_start rc: ' + str(rc))
                time.sleep(10)
            else:
                try:
                    with open('data/i2c_reset', 'r') as f:
                        i2c_reset = True
                        logger.warning('file i2c_reset')
                        if i2c_reset:
                            subprocess.call(['rm', 'data/i2c_reset'])
                except:
                    pass

                print 'checking i2c reset', i2c_reset
                if i2c_reset:
                    # Factory reset request
                    boards = i2c.get_vsb_boards()
                    for board, version in boards.items():
                        if board not in gv.in_bootloader:
                            logger.warning('i2c reset board: ' +
                                           str(board + 1))
                            i2c.i2c_reset(i2c.ADDRESS + board)
                        else:
                            logger.critical('i2c reset aborted board: ' +
                                            str(board + 1) +
                                            ' in bootloader version: ' +
                                            hex(version))
                    logger.info('reboot.')
                    reboot(0, True)

        except Exception as ex:
            logger.critical('check_factory_reset exception: ' + str(ex))
Beispiel #8
0
    def GET(self):
        qdict = web.input()
        try:
            ddict = json.loads(qdict['data'])
        except:
            raise web.unauthorized()

        force_reboot = False
        info = {}
        for l in ['wlog', 'elog', 'slog', 'evlog']:
            if l in ddict and ddict[l]:
                end = ddict['end_date']
                days = ddict['days_before']
                prefix = ''
                try:
                    if l in ['slog', 'evlog']:
                        prefix = 'sensors/' + gv.plugin_data['ld'][int(ddict['ldi'])]['name'] + '/logs/'
                except:
                    pass
                records = read_log(prefix+l, end, days)
                info[l] = records

        for dlog in ['dlogirricloud', 'dlogirricloud_monitor', 'dlogirricloud_net_config']:
            if dlog in ddict and ddict[dlog]:
                records = []
                try:
                    with open('./logs/' + dlog[4:] + '.out', 'r') as file:
                        records = file.readlines()
                except:
                    pass
                info[dlog] = []
                for r in records:
                    info[dlog].append(r)

        if 'lrun' in ddict and ddict['lrun']:
            info['lrun'] = gv.lrun

        if 'programs' in ddict:
            if ddict['programs'] == 1:
                info['programs'] = gv.pd
            else:
                gv.pd = ddict['programs']
                jsave(gv.pd, 'programs')
                info['programs'] = 1

        if 'ps' in ddict and ddict['ps']:
            info['ps'] = gv.ps

        if 'sbits' in ddict and ddict['sbits']:
            info['sbits'] = gv.sbits

        if 'srvals' in ddict and ddict['srvals']:
            info['srvals'] = gv.srvals

        if 'sensors' in ddict and 'ld' in gv.plugin_data:
            if ddict['sensors'] == 1:
                info['sensors'] = []
                try:
                    if 'ldi' not in ddict or int(ddict['ldi']) == -1:
                        info['sensors'] = gv.plugin_data['ld']
                    else:
                        info['sensors'] = gv.plugin_data['ld'][int(ddict['ldi'])]
                except:
                    pass
                info['sensboards'] = i2c.get_vsb_boards().keys()
                info['remotesensboards'] = get_remote_sensor_boards()
            else:
                try:
                    if 'ldi' not in ddict or int(ddict['ldi']) == -1:
                        gv.plugin_data['ld'] = ddict['sensors']
                    else:
                        gv.plugin_data['ld'][int(ddict['ldi'])] = ddict['sensors']
                except:
                    gv.plugin_data['ld'] = ddict['sensors']
                jsave(gv.plugin_data['ld'], 'sensors')
                info['sensors'] = 1

        if 'camera' in ddict and 'ca' in gv.plugin_data:
            if ddict['camera'] == 1:
                info['camera'] = gv.plugin_data['ca']
                if 'cai' in ddict and ddict['cai']:
                    info['cai'] = ''
                    if gv.plugin_data['ca']['enable_camera'] == 'on':
                        try:
                            with open('./static/images/camera.jpg', mode='rb') as file: # b is important -> binary
                                info['cai'] = base64.b64encode(file.read())
                        except:
                            pass
            else:
                gv.plugin_data['ca'] = ddict['camera']
                jsave(gv.plugin_data['ca'], 'camera')
                info['camera'] = 1

        if 'sd' in ddict:
            if ddict['sd'] == 1:
                sd = gv.sd.copy()
                del sd['substation_network']
                del sd['salt']
                del sd['password']
                del sd['pwd']
                del sd['enable_upnp'] # stuff from base configuration stays as was
                del sd['subnet_only_substations']
                del sd['external_proxy_port']
                kill_keys = []
                for k,v in sd.iteritems():
                    if len(k) > 2 and (k[0:2] == 'te' or k[0:2] == 'et'):
                        kill_keys.append(k)
                for k in kill_keys:
                    del sd[k] # dont send textemail or et_weather stuff
                info['sd'] = sd
            else:
                for field in ddict['sd']:
                    gv.sd[field] = ddict['sd'][field]
                update_hostname(gv.sd['name'])
                update_tza(gv.sd['tza'])
                jsave(gv.sd, 'sd')
                info['sd'] = 1
                force_reboot = True

        if 'snames' in ddict:
            if ddict['snames'] == 1:
                info['snames'] = gv.snames
            else:
                gv.snames = ddict['snames']
                jsave(gv.snames, 'snames')
                info['snames'] = 1

        if 'snotes' in ddict:
            if ddict['snotes'] == 1:
                info['snotes'] = gv.snotes
            else:
                gv.snotes = ddict['snotes']
                jsave(gv.snotes, 'snotes')
                info['snotes'] = 1

        if 'update_status' in ddict and ddict['update_status']:
            updatechecker.update_rev_data()
            info['update_status'] = updatechecker.status

        web.header('Content-Type', 'application/json')
        ret_str = json.dumps(info)
        if force_reboot:
            reboot(5)  # give a few seconds to reply
        return ret_str
Beispiel #9
0
    def run(self):
        if disable_substations:
            return        

        gv.logger.info('Substation plugin started')        
        time.sleep(7) # let things wake up, but keep less than delay for sending email

        last_message_base = gv.now - 60
        while True:
            try:
                if gv.sd['slave'] and gv.now - last_message_base >= 60:
                    try:
                        last_message_base = gv.now
                        data = message_base('suslj')
                        if 'unreachable' in data:
                            raise IOError, 'UnreachableMaster'
                        force_reboot = False
                        # update common data that has changed on the master
                        for grouping in data:
                            if gv.sd['master']:
                                continue
                            for key in data[grouping]:
                                if grouping == 'sd':
                                    if key in gv.sd:
                                        if gv.sd[key] != data['sd'][key]:
                                            gv.logger.info('Changing gv.sd[' + key + '] from ' + str(gv.sd[key]) + ' to ' + str(data['sd'][key]))
                                            if key == 'remote_support_port' and gv.sd['enable_upnp']:
                                                gv.logger.critical('substation_run: Unexpected key of remote_support_port')
                                                if gv.sd[key] != 0: # delete old
                                                    update_upnp(get_ip(), [gv.sd[key]])
                                                if data['sd'][key] != 0:
                                                    update_upnp(get_ip(), [], [[22, data['sd'][key]]])
                                            gv.sd[key] = data['sd'][key]
                                            if key == 'tza':
                                                with open('/etc/timezone','w') as file:
                                                    file.write(qdict['o'+f]+'\n')
                                                subprocess.call(['dpkg-reconfigure', '-f', 'non-interactive', 'tzdata'])
                                                force_reboot = True
                                            elif key == 'loc' or key == 'lang':
                                                force_reboot = True
                                    else:
                                        gv.logger.info('Setting gv.sd[' + key + '] to ' + str(data['sd'][key]))
                                        gv.sd[key] = data['sd'][key]
                                elif grouping in gv.plugin_data:
                                    if key in gv.plugin_data[grouping]:
                                        if gv.plugin_data[grouping][key] != data[grouping][key]:
                                            gv.logger.info('Changing gv.plugin_data[' + grouping +'][' + key + '] from ' + str(gv.plugin_data[grouping][key]) + ' to ' + str(data[grouping][key]))
                                            gv.plugin_data[grouping][key] = data[grouping][key]
                                    else:
                                        gv.logger.info('Setting gv.plugin_data[' + grouping +'][' + key + '] to ' + str(data[grouping][key]))
                                        gv.plugin_data[grouping][key] = data[grouping][key]
                                elif grouping == 'other':
                                    if key == 'websession':
                                        web.config._session.user = data[grouping][key]
                                    elif key == 'datetime':
                                        try:
                                            pass
#                                            subprocess.call(['date', '--set='+data[grouping][key]])
                                        except:
                                            gv.logger.exception('Could not set datetime to ' + data[grouping][key])
                            if grouping == 'sd':
                                jsave(gv.sd, 'sd')
                            elif grouping != 'other':
                                pass
                        if force_reboot:
                            reboot(5) # give a few seconds before reboot

                    except Exception as ex:
                        gv.logger.info('No master response.  ip: ' + get_ip_to_base() + \
                                       ' port: ' + str(gv.sd['master_port']) + \
                                       ' Exception: ' + str(ex))
                        try:
                            iwout = subprocess.check_output(['iwconfig', 'wlan0'])
                            lines = iwout.split('\n')
                            for l in lines:
                                if 'ESSID:' in l:
                                    gv.logger.info('slave iwconfig wlan0 ' + l[l.find('ESSID:'):])
                        except Exception as ex:
                            gv.logger.info('slave could not check iwconfig: ' + str(ex))

                if gv.sd['master']:
                    for subid in range(1,len(gv.plugin_data['su']['subinfo'])):
                        sub = gv.plugin_data['su']['subinfo'][subid]
                        try:
                            if sub['status'] != 'unreachable' and gv.now - sub['last_join'] >= 90: # if havent received join in a while reach out
                                qd = {'substation':subid}
                                load_and_save_remote(qd, [], 'susldr', 'data', {}) # touch a slave to ensure still alive
                        except Exception as ex:
                            gv.logger.info('substations reach out to slave: No response from slave: ' +
                                           sub['name'] + ' Exception: ' + str(ex))
                            sub['status'] = 'unreachable'
                            try:
                                iwout = subprocess.check_output(['iwconfig', 'wlan0'])
                                lines = iwout.split('\n')
                                for l in lines:
                                    if 'ESSID:' in l:
                                        gv.logger.info('master iwconfig wlan0 ' + l[l.find('ESSID:'):])
                            except Exception as ex:
                                gv.logger.info('master could not check iwconfig: ' + str(ex))

            except Exception as ex:
                self.start_status('', 'Substation encountered error: ' + str(ex))

            self._sleep(30)
Beispiel #10
0
def check_factory_reset():
    """Check every five seconds to see if we need to do a factory reset"""
    global config_mode

    while True:
        time.sleep(5)
        try:
            factory_reset = False
            i2c_reset = False
            try:
                # if factory_reset file is present or hw button is pushed.
                if pi.read(button_pin) == 0:
                    factory_reset = True
                    logger.warning('button factory reset')
                else:
                    try:
                        with open('data/factory_reset','r') as f:
                            factory_reset = True
                            logger.warning('file factory reset')
                        if factory_reset:
                            subprocess.call(['rm', 'data/factory_reset'])
                    except:
                        pass
            except Exception as ex:
                logger.warning('button read failure: ' + str(ex))

            if factory_reset:
                # Factory reset request
                logger.warning('factory reset')
                light_vsb_boards()
                try:
                    type = ''
                    usbs = subprocess.check_output(['lsusb'])
                    usbl = usbs.split('\n')
                    for usb in usbl:
                        if 'Ralink Technology' in usb:
                            type = 'CanaKit' if type == '' else 'Unknown'
                        elif 'Realtek Semiconductor' in usb:
                           type = 'TP' if type == '' else 'Unknown'

                    if type != '' and type != 'Unknown':
                        for file in ['/etc/hostapd/hostapd.conf', '/usr/sbin/hostapd', '/etc/wpa_supplicant/functions.sh']:
                            rc = subprocess.call(['diff', file, file+'-'+type])
                            if rc == 0:
                                logger.debug(file + ' and ' + file+'-'+type + ' match')
                            else:
                                logger.critical('Rebinding ' + file + ' to match ' + file+'-'+type)
                                subprocess.call(['rm', file])
                                subprocess.call(['ln', '-s', file+'-'+type, file])
                    else:
                        logger.info('leaving hostapd and wpa_supplicant unchanged.  type: ' + type)
                         
                except Exception as ex:
                    logger.exception('Could not validate/change hostapd and wpa_supplicant usage: ' + str(ex))
                logger.info('restoring orig /etc/network/interfaces and /etc/wpa_supplicant/wpa_supplicant.conf')
                config_mode = True
                shutil.copy2('/etc/network/interfaces.orig', '/etc/network/interfaces')
                shutil.copy2('/etc/wpa_supplicant/wpa_supplicant.conf.orig', '/etc/wpa_supplicant/wpa_supplicant.conf')
                shutil.copy2('/etc/dhcpcd.conf.orig', '/etc/dhcpcd.conf')
                logger.info('starting sip_net_start')
                rc = subprocess.call(['/usr/bin/python', '/home/pi/Irricloud/sip_net_start.py']) # leads to reboot
                logger.debug( 'sip_net_start rc: ' + str(rc))
                time.sleep(10)
            else:
                try:
                    with open('data/i2c_reset','r') as f:
                        i2c_reset = True
                        logger.warning('file i2c_reset')
                        if i2c_reset:
                            subprocess.call(['rm', 'data/i2c_reset'])
                except:
                    pass

                if i2c_reset:
                    # Factory reset request
                    boards = i2c.get_vsb_boards()
                    for board, version in boards.items():
                        if board not in gv.in_bootloader:
                            logger.warning('i2c reset board: ' + str(board+1))
                            i2c.i2c_reset(i2c.ADDRESS+board)
                        else:
                            logger.critical('i2c reset aborted board: ' + str(board+1) + ' in bootloader version: ' + hex(version))
                    logger.info('reboot.')
                    reboot(0, True)

        except Exception as ex:
            logger.critical('check_factory_reset exception: ' + str(ex))