Beispiel #1
0
 def GET(self):
     qdict = web.input()
     if 'substation' not in qdict:
         qdict['substation'] = str(gv.substation_index)
     subid = int(qdict['substation'])
     subprocess.call(['rm', 'static/images/camera_temp.jpg'])
     if process_page_request('view_camera', qdict):
         if gv.plugin_data['ca']['enable_camera'] == 'on':
             subprocess.call(['cp', 'static/images/camera.jpg', 'static/images/camera_temp.jpg'])
         return template_render.camera(0, gv.plugin_data['ca'])
     elif 'substation' not in qdict:
         raise web.seeother('/suslv?head=Cameras&continuation=ca')
     else:
         try:
             subid, data = load_and_save_remote(qdict, [], 'susldr', 'data', {'camera':1, 'cai':1})
             if data['cai']:
                 try:
                     with open('static/images/camera_temp.jpg', mode='wb') as file: # b is important -> binary
                         file.write(base64.b64decode(data['cai']))
                 except Exception as ex:
                     gv.logger.critical('Could not write camera_temp.jpg.  ex: ' + str(ex))
             return template_render.camera(subid, data['camera'])
         except Exception as ex:
             gv.logger.exception('view_camera: No response from slave: ' +
                            gv.plugin_data['su']['subinfo'][subid]['name'] + ' Exception: ' + str(ex))
             gv.plugin_data['su']['subinfo'][subid]['status'] = 'unreachable'
             raise web.seeother('/unreachable')
Beispiel #2
0
 def GET(self):
     qdict = web.input()
     if 'head' not in qdict or 'continuation' not in qdict:
         raise web.unauthorized()
     head = qdict['head']
     cont = qdict['continuation']
     # loop through substations for reachability
     for subid in range(1,len(gv.plugin_data['su']['subinfo'])):
         try:
             qd = {'substation':subid}
             load_and_save_remote(qd, [], 'susldr', 'data', {})
         except Exception as ex:
             gv.logger.info('view_substations: No response from slave: ' +
                            gv.plugin_data['su']['subinfo'][subid]['name'] + ' Exception: ' + str(ex))
             gv.plugin_data['su']['subinfo'][subid]['status'] = 'unreachable'
     return template_render.substations(head, cont, gv.plugin_data['su']['subinfo'])
Beispiel #3
0
 def GET(self):
     qdict = web.input()
     if 'head' not in qdict or 'continuation' not in qdict:
         raise web.unauthorized()
     head = qdict['head']
     cont = qdict['continuation']
     # loop through substations for reachability
     for subid in range(1,len(gv.plugin_data['su']['subinfo'])):
         try:
             qd = {'substation':subid}
             load_and_save_remote(qd, [], 'susldr', 'data', {})
         except Exception as ex:
             gv.logger.info('view_substations: No response from slave: ' +
                            gv.plugin_data['su']['subinfo'][subid]['name'] + ' Exception: ' + str(ex))
             gv.plugin_data['su']['subinfo'][subid]['status'] = 'unreachable'
     return template_render.substations(head, cont, gv.plugin_data['su']['subinfo'])
Beispiel #4
0
    def GET(self):
        qdict = web.input()
        subid = 0 if 'substation' not in qdict else int(qdict['substation'])
        if process_page_request('change_camera', qdict) or subid == 0:
            checkboxes = ['enable_camera', 'zone_pic', 'current_pic']
            for c in checkboxes:
                if c != 'enable_camera' or gv.plugin_data['ca'][c] != 'missing':
                    if c not in qdict:
                        qdict[c] = 'off'
                else:
                    qdict[
                        c] = 'missing'  # dont change 'missing' attribute of enable_camera

            for c in checkboxes:
                if gv.plugin_data['ca'][c] != qdict[c]:
                    gv.plugin_data['ca'][c] = qdict[c]
                    changed = True

            intparams = ['sleep_time']
            for p in intparams:
                if gv.plugin_data['ca'][p] != int(qdict[p]):
                    gv.plugin_data['ca'][p] = int(qdict[p])
                    changed = True

            sparams = ['resolution']
            for p in sparams:
                if gv.plugin_data['ca'][p] != qdict[p]:
                    gv.plugin_data['ca'][p] = qdict[p]
                    take_picture('camera.jpg', False)
                    changed = True

            if changed:
                with open('./data/camera.json',
                          'w') as f:  # write the settings to file
                    json.dump(gv.plugin_data['ca'], f)
            if 'substation' in qdict:
                web.header('Content-Type', 'application/json')
                return json.dumps([])
        else:
            try:
                subid, data = load_and_save_remote(qdict, [], 'cau',
                                                   'substation', '0')
            except Exception as ex:
                gv.logger.info('change_camera: No response from slave: ' +
                               gv.plugin_data['su']['subinfo'][subid]['name'] +
                               ' Exception: ' + str(ex))
                gv.plugin_data['su']['subinfo'][subid][
                    'status'] = 'unreachable'
                raise web.seeother('/unreachable')
        raise web.seeother('/ca')
Beispiel #5
0
 def GET(self):
     qdict = web.input()
     subid = 0 if 'substation' not in qdict else int(qdict['substation'])
     if process_page_request('pic', qdict) or subid == 0:
         take_picture('camera.jpg', False)
         if 'substation' in qdict:
             web.header('Content-Type', 'application/json')
             return json.dumps([])
     else:
         try:
             subid, data = load_and_save_remote(qdict, [], 'cap', 'substation', '0')
         except Exception as ex:
             gv.logger.info('pic: No response from slave: ' +
                            gv.plugin_data['su']['subinfo'][subid]['name'] + ' Exception: ' + str(ex))
             gv.plugin_data['su']['subinfo'][subid]['status'] = 'unreachable'
             raise web.seeother('/unreachable')
     raise web.seeother('/ca')
Beispiel #6
0
    def GET(self):
        qdict = web.input()
        subid = 0 if 'substation' not in qdict else int(qdict['substation'])
        if process_page_request('change_camera', qdict) or subid == 0:
            checkboxes = ['enable_camera', 'zone_pic','current_pic']
            for c in checkboxes:
                if c != 'enable_camera' or gv.plugin_data['ca'][c] != 'missing':
                    if c not in qdict:
                        qdict[c] = 'off'
                else:
                    qdict[c] = 'missing' # dont change 'missing' attribute of enable_camera

            for c in checkboxes:
                if gv.plugin_data['ca'][c] != qdict[c]:
                    gv.plugin_data['ca'][c] = qdict[c]
                    changed = True

            intparams = ['sleep_time']
            for p in intparams:
                if gv.plugin_data['ca'][p] != int(qdict[p]):
                    gv.plugin_data['ca'][p] = int(qdict[p])
                    changed = True

            sparams = ['resolution']
            for p in sparams:
                if gv.plugin_data['ca'][p] != qdict[p]:
                    gv.plugin_data['ca'][p] = qdict[p]
                    take_picture('camera.jpg', False)
                    changed = True

            if changed:
                with open('./data/camera.json', 'w') as f:  # write the settings to file
                    json.dump(gv.plugin_data['ca'], f)
            if 'substation' in qdict:
                web.header('Content-Type', 'application/json')
                return json.dumps([])
        else:
            try:
                subid, data = load_and_save_remote(qdict, [], 'cau', 'substation', '0')
            except Exception as ex:
                gv.logger.info('change_camera: No response from slave: ' +
                               gv.plugin_data['su']['subinfo'][subid]['name'] + ' Exception: ' + str(ex))
                gv.plugin_data['su']['subinfo'][subid]['status'] = 'unreachable'
                raise web.seeother('/unreachable')
        raise web.seeother('/ca')
Beispiel #7
0
 def GET(self):
     qdict = web.input()
     subid = 0 if 'substation' not in qdict else int(qdict['substation'])
     if process_page_request('pic', qdict) or subid == 0:
         take_picture('camera.jpg', False)
         if 'substation' in qdict:
             web.header('Content-Type', 'application/json')
             return json.dumps([])
     else:
         try:
             subid, data = load_and_save_remote(qdict, [], 'cap',
                                                'substation', '0')
         except Exception as ex:
             gv.logger.info('pic: No response from slave: ' +
                            gv.plugin_data['su']['subinfo'][subid]['name'] +
                            ' Exception: ' + str(ex))
             gv.plugin_data['su']['subinfo'][subid][
                 'status'] = 'unreachable'
             raise web.seeother('/unreachable')
     raise web.seeother('/ca')
Beispiel #8
0
 def GET(self):
     qdict = web.input()
     if 'substation' not in qdict:
         qdict['substation'] = str(gv.substation_index)
     subid = int(qdict['substation'])
     subprocess.call(['rm', 'static/images/camera_temp.jpg'])
     if process_page_request('view_camera', qdict):
         if gv.plugin_data['ca']['enable_camera'] == 'on':
             subprocess.call([
                 'cp', 'static/images/camera.jpg',
                 'static/images/camera_temp.jpg'
             ])
         return template_render.camera(0, gv.plugin_data['ca'])
     elif 'substation' not in qdict:
         raise web.seeother('/suslv?head=Cameras&continuation=ca')
     else:
         try:
             subid, data = load_and_save_remote(qdict, [], 'susldr', 'data',
                                                {
                                                    'camera': 1,
                                                    'cai': 1
                                                })
             if data['cai']:
                 try:
                     with open(
                             'static/images/camera_temp.jpg',
                             mode='wb') as file:  # b is important -> binary
                         file.write(base64.b64decode(data['cai']))
                 except Exception as ex:
                     gv.logger.critical(
                         'Could not write camera_temp.jpg.  ex: ' + str(ex))
             return template_render.camera(subid, data['camera'])
         except Exception as ex:
             gv.logger.exception(
                 'view_camera: No response from slave: ' +
                 gv.plugin_data['su']['subinfo'][subid]['name'] +
                 ' Exception: ' + str(ex))
             gv.plugin_data['su']['subinfo'][subid][
                 'status'] = 'unreachable'
             raise web.seeother('/unreachable')
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
        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 #10
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)