Example #1
0
def dashboard():
    """ Codigo que maneja el dashboard de la aplicacion. """

    createDB()
    products = queryDB("SELECT id, name FROM products;")

    kwargs = {}
    kwargs["title"] = PAGE_DASHBOARD[1]
    kwargs["serverAddr"] = CONFIG["NC_ADDRESS"]
    kwargs["serverPort"] = CONFIG["SERVER_PORT"]
    kwargs["products"] = products
    kwargs["selected_product"] = CONFIG["CURRENT_PRODUCT"]

    if request.method == "POST":

        currentProduct = int(request.form["currentProduct"])
        min_weight, max_weight = queryDB(
            "SELECT min_weight, max_weight FROM products WHERE id = ?", (currentProduct,), one=True
        )

        if app.mutex.acquire(False):
            CONFIG["CURRENT_PRODUCT"] = currentProduct
            utils.writeConfig(CONFIG, APP_CONFIG_PATH)
            kwargs["selected_product"] = currentProduct
            print(currentProduct)
            arduino.setWeights(min_weight, max_weight)
            flash("Se cambio el producto actual!")
            app.mutex.release()
        else:
            flash(u"Dispositivo ocupado, alguien más intenta actualizarlo!")

    destroyDB()

    return render_template("dashboard.html", **kwargs)
Example #2
0
def dashboard():
    ''' Codigo que maneja el dashboard de la aplicacion. '''

    createDB()
    products = queryDB('SELECT id, name FROM products;')

    kwargs = {}
    kwargs['title'] = PAGE_DASHBOARD[1]
    kwargs['serverAddr'] = CONFIG['NC_ADDRESS']
    kwargs['serverPort'] = CONFIG['SERVER_PORT']
    kwargs['products'] = products
    kwargs['selected_product'] = CONFIG['CURRENT_PRODUCT']

    if request.method == 'POST':

        currentProduct = int(request.form['currentProduct'])
        min_weight, max_weight = queryDB(
            'SELECT min_weight, max_weight FROM products WHERE id = ?',
            (currentProduct, ),
            one=True)

        if app.mutex.acquire(False):
            CONFIG['CURRENT_PRODUCT'] = currentProduct
            utils.writeConfig(CONFIG, APP_CONFIG_PATH)
            kwargs['selected_product'] = currentProduct
            print(currentProduct)
            arduino.setWeights(min_weight, max_weight)
            flash('Se cambio el producto actual!')
            app.mutex.release()
        else:
            flash(u'Dispositivo ocupado, alguien más intenta actualizarlo!')

    destroyDB()

    return render_template('dashboard.html', **kwargs)
Example #3
0
 def doSave(self):
     if not self.validateConfig():
         QMessageBox.critical(None,
                              "Error", "Configuration has errors, not saved!",
                              QMessageBox.Ok, QMessageBox.Ok)
         return False
     # Do we want to SVN it?!?
     d = self.commitdialog
     d.setWindowTitle("SVN Commit %s" % self.hutch)
     d.ui.commentEdit.setPlainText("")
     while True:
         d.exec_()
         if d.result == QDialogButtonBox.Cancel:
             return False
         if d.result == QDialogButtonBox.No:
             comment = None
             break
         comment = str(d.ui.commentEdit.toPlainText())
         if comment != "":
             break
         QMessageBox.critical(None,
                              "Error", "Must have a comment for SVN commit for %s" % self.hutch,
                              QMessageBox.Ok, QMessageBox.Ok)
     try:
         file = tempfile.NamedTemporaryFile(dir=utils.TMP_DIR, delete=False)
         utils.writeConfig(self.hutch, self.hosts, self.cfglist, self.vdict, file)
         file.close()
         os.chmod(file.name, stat.S_IRUSR | stat.S_IRGRP |stat.S_IROTH)
         utils.installConfig(self.hutch, file.name, self.userIO)
         try:
             os.remove(file.name)
         except:
             pass
     except:
         QMessageBox.critical(None,
                              "Error", "Failed to write configuration for %s" % self.hutch,
                              QMessageBox.Ok, QMessageBox.Ok)
         return False
     for entry in self.cfglist:
         #
         # IOC names are special.  If we just reprocess the file, we will have both the
         # old *and* the new names!  So we have to change the names here.
         #
         try:
             entry['id'] = entry['newid'].strip()
             del entry['newid']
         except:
             pass
         try:
             del entry['details']
         except:
             pass
     if comment != None:
         try:
             utils.commit_config(self.hutch, comment, self.userIO)
         except:
             pass
     return True
Example #4
0
def do_commit(hutch, cl, hl, vs):
    file = tempfile.NamedTemporaryFile(dir=utils.TMP_DIR, delete=False)
    utils.writeConfig(hutch, hl, cl, vs, file)
    file.close()
    os.chmod(file.name, stat.S_IRUSR | stat.S_IRGRP |stat.S_IROTH)
    os.system("ssh %s %s %s %s" % (utils.COMMITHOST, utils.INSTALL, hutch, file.name))
    try:
        os.unlink(file.name)
    except:
        print "Error removing temporary file %s!" % file.name
Example #5
0
def changepass():
    """ Codigo que cambia los credenciales. """
    if request.method == "POST":

        oldpass = hashlib.sha512(request.form["oldpass"]).hexdigest()
        newpass1 = request.form["newpass1"]
        newpass2 = request.form["newpass2"]

        if oldpass == CONFIG["WEB_PASSWORD"] and len(newpass1) >= 6 and newpass1 == newpass2:
            # Intentamos adquirir el mutex, sin bloquear.
            if app.mutex.acquire(False):
                CONFIG["WEB_PASSWORD"] = hashlib.sha512(newpass1).hexdigest()
                utils.writeConfig(CONFIG, APP_CONFIG_PATH)
                app.mutex.release()
                flash(u"Contraseña actualizada con éxito.")
                return redirect(url_for("logout"))
            else:
                flash(u"Dispositivo ocupado, alguien más intenta actualizarlo!")
        else:
            flash(u"Error: alguno de los campos es inválido.")

    return render_template("changepass.html", title=u"Cambiar contraseña")
Example #6
0
def changepass():
    ''' Codigo que cambia los credenciales. '''
    if request.method == 'POST':

        oldpass = hashlib.sha512(request.form['oldpass']).hexdigest()
        newpass1 = request.form['newpass1']
        newpass2 = request.form['newpass2']

        if oldpass == CONFIG['WEB_PASSWORD'] and len(
                newpass1) >= 6 and newpass1 == newpass2:
            # Intentamos adquirir el mutex, sin bloquear.
            if app.mutex.acquire(False):
                CONFIG['WEB_PASSWORD'] = hashlib.sha512(newpass1).hexdigest()
                utils.writeConfig(CONFIG, APP_CONFIG_PATH)
                app.mutex.release()
                flash(u'Contraseña actualizada con éxito.')
                return redirect(url_for('logout'))
            else:
                flash(
                    u'Dispositivo ocupado, alguien más intenta actualizarlo!')
        else:
            flash(u'Error: alguno de los campos es inválido.')

    return render_template('changepass.html', title=u'Cambiar contraseña')
Example #7
0
def updateNetworkConfiguration(netType, netConfig, wpaConfig):
    """ Actualiza la configuracion de red.
        netType: static | dynamic
        netConfig: (address, network, netmask, broadcast, gateway)
        wpaConfig: (ssid, psk)
        appConfig: archivo de configuracion de la aplicacion
        Consulte "man ifconfig" para informacion de configuracion.
    """

    # Intentamos actualizar las interfaces de red.
    if netType is not None and netConfig is not None:
        interfacesTemplate = None
        template = "ncstatic" if "static" == netType else "ncdynamic"
        with open(os.path.join(APP_PATH, template), "r") as templateFile:
            interfacesTemplate = templateFile.read()
            templateFile.close()

        # Ocurrio un error, retornamos.
        if interfacesTemplate is None:
            return False

        if "static" == netType:

            interfacesNew = interfacesTemplate
            for i, text in enumerate(netConfig):
                interfacesNew = interfacesNew.replace("{%s}" % i, text)
        else:
            interfacesNew = interfacesTemplate  # verbatim

        # Intentamos adquirir el mutex, sin bloquear.
        if app.mutex.acquire(False):
            with open(INTERFACE_FILE_PATH, "w") as interfacesFile:
                interfacesFile.write(interfacesNew)
                interfacesFile.close()

                # Actualizamos la configuracion.
                CONFIG["NC_TYPE"] = "static" if "static" == netType else "dynamic"
                utils.writeConfig(CONFIG, APP_CONFIG_PATH)
            app.mutex.release()
        else:
            raise DeviceBusyError()

    # Intentamos actualizar la configuracion de WPA Supplicant.
    if wpaConfig is not None:
        wpaTemplate = None
        with open(os.path.join(APP_PATH, "ncwpa"), "r") as templateFile:
            wpaTemplate = templateFile.read()
            templateFile.close()

        # Ocurrio un error, retornamos.
        if wpaTemplate is None:
            return False

        wpaNew = wpaTemplate.replace("{0}", wpaConfig[0]).replace("{1}", wpaConfig[1])

        # Intentamos adquirir el mutex, sin bloquear.
        if app.mutex.acquire(False):
            with open(WPA_FILE_PATH, "w") as wpaFile:
                wpaFile.write(wpaNew)
                wpaFile.close()

                # Actualizamos la configuracion.
                CONFIG["NC_WPA_SSID"], CONFIG["NC_WPA_PSK"] = wpaConfig
                utils.writeConfig(CONFIG, APP_CONFIG_PATH)
            app.mutex.release()
        else:
            raise DeviceBusyError()

    return True
Example #8
0
def updateNetworkConfiguration(netType, netConfig, wpaConfig):
    ''' Actualiza la configuracion de red.
        netType: static | dynamic
        netConfig: (address, network, netmask, broadcast, gateway)
        wpaConfig: (ssid, psk)
        appConfig: archivo de configuracion de la aplicacion
        Consulte "man ifconfig" para informacion de configuracion.
    '''

    # Intentamos actualizar las interfaces de red.
    if netType is not None and netConfig is not None:
        interfacesTemplate = None
        template = 'ncstatic' if 'static' == netType else 'ncdynamic'
        with open(os.path.join(APP_PATH, template), 'r') as templateFile:
            interfacesTemplate = templateFile.read()
            templateFile.close()

        # Ocurrio un error, retornamos.
        if interfacesTemplate is None:
            return False

        if 'static' == netType:

            interfacesNew = interfacesTemplate
            for i, text in enumerate(netConfig):
                interfacesNew = interfacesNew.replace('{%s}' % i, text)
        else:
            interfacesNew = interfacesTemplate  # verbatim

        # Intentamos adquirir el mutex, sin bloquear.
        if app.mutex.acquire(False):
            with open(INTERFACE_FILE_PATH, 'w') as interfacesFile:
                interfacesFile.write(interfacesNew)
                interfacesFile.close()

                # Actualizamos la configuracion.
                CONFIG[
                    'NC_TYPE'] = 'static' if 'static' == netType else 'dynamic'
                utils.writeConfig(CONFIG, APP_CONFIG_PATH)
            app.mutex.release()
        else:
            raise DeviceBusyError()

    # Intentamos actualizar la configuracion de WPA Supplicant.
    if wpaConfig is not None:
        wpaTemplate = None
        with open(os.path.join(APP_PATH, 'ncwpa'), 'r') as templateFile:
            wpaTemplate = templateFile.read()
            templateFile.close()

        # Ocurrio un error, retornamos.
        if wpaTemplate is None:
            return False

        wpaNew = wpaTemplate.replace('{0}', wpaConfig[0]).replace(
            '{1}', wpaConfig[1])

        # Intentamos adquirir el mutex, sin bloquear.
        if app.mutex.acquire(False):
            with open(WPA_FILE_PATH, 'w') as wpaFile:
                wpaFile.write(wpaNew)
                wpaFile.close()

                # Actualizamos la configuracion.
                CONFIG['NC_WPA_SSID'], CONFIG['NC_WPA_PSK'] = wpaConfig
                utils.writeConfig(CONFIG, APP_CONFIG_PATH)
            app.mutex.release()
        else:
            raise DeviceBusyError()

    return True