Exemple #1
0
def func_add(form_add_func):
    action = '{action} {controller}'.format(
        action=gettext("Add"),
        controller=gettext("Function"))
    error = []

    if form_add_func.validate():
        try:
            if [ur for ur in PIDS if form_add_func.func_type.data == ur[0]]:
                new_func = PID().save()
                if not error:
                    display_order = csv_to_list_of_str(
                        DisplayOrder.query.first().pid)
                    DisplayOrder.query.first().pid = add_display_order(
                        display_order, new_func.unique_id)
                    db.session.commit()
            elif [ur for ur in CONDITIONALS if form_add_func.func_type.data == ur[0]]:
                new_func = Conditional()
                new_func.conditional_type = form_add_func.func_type.data
                new_func.save()
                if not error:
                    display_order = csv_to_list_of_str(
                        DisplayOrder.query.first().conditional)
                    DisplayOrder.query.first().conditional = add_display_order(
                        display_order, new_func.unique_id)
                    db.session.commit()

        except sqlalchemy.exc.OperationalError as except_msg:
            error.append(except_msg)
        except sqlalchemy.exc.IntegrityError as except_msg:
            error.append(except_msg)
        flash_success_errors(error, action, url_for('routes_page.page_function'))
    else:
        flash_form_errors(form_add_func)
Exemple #2
0
def input_del(input_id):
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['delete']['title'],
        controller=TRANSLATIONS['input']['title'])
    error = []

    try:
        input_dev = Input.query.filter(Input.unique_id == input_id).first()

        if input_dev.is_activated:
            input_deactivate_associated_controllers(input_id)
            controller_activate_deactivate('deactivate', 'Input', input_id)

        device_measurements = DeviceMeasurements.query.filter(
            DeviceMeasurements.device_id == input_id).all()

        for each_measurement in device_measurements:
            delete_entry_with_id(DeviceMeasurements,
                                 each_measurement.unique_id)

        delete_entry_with_id(Input, input_id)
        try:
            display_order = csv_to_list_of_str(
                DisplayOrder.query.first().inputs)
            display_order.remove(input_id)
            DisplayOrder.query.first().inputs = list_to_csv(display_order)
        except Exception:  # id not in list
            pass
        db.session.commit()
    except Exception as except_msg:
        error.append(except_msg)

    flash_success_errors(error, action, url_for('routes_page.page_data'))
Exemple #3
0
def math_del(form_mod_math):
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['delete']['title'],
        controller=TRANSLATIONS['math']['title'])
    error = []

    math_id = form_mod_math.math_id.data

    try:
        math = Math.query.filter(Math.unique_id == math_id).first()
        if math.is_activated:
            controller_activate_deactivate('deactivate', 'Math',
                                           form_mod_math.math_id.data)

        device_measurements = DeviceMeasurements.query.filter(
            DeviceMeasurements.device_id == math_id).all()

        for each_measurement in device_measurements:
            delete_entry_with_id(DeviceMeasurements,
                                 each_measurement.unique_id)

        delete_entry_with_id(Math, math_id)
        try:
            display_order = csv_to_list_of_str(DisplayOrder.query.first().math)
            display_order.remove(math_id)
            DisplayOrder.query.first().math = list_to_csv(display_order)
        except Exception:  # id not in list
            pass
        db.session.commit()
    except Exception as except_msg:
        error.append(except_msg)

    flash_success_errors(error, action, url_for('routes_page.page_input'))
Exemple #4
0
def input_del(input_id):
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['delete']['title'],
        controller=TRANSLATIONS['input']['title'])
    error = []

    try:
        input_dev = Input.query.filter(
            Input.unique_id == input_id).first()

        if input_dev.is_activated:
            input_deactivate_associated_controllers(input_id)
            controller_activate_deactivate('deactivate', 'Input', input_id)

        device_measurements = DeviceMeasurements.query.filter(
            DeviceMeasurements.device_id == input_id).all()

        for each_measurement in device_measurements:
            delete_entry_with_id(DeviceMeasurements, each_measurement.unique_id)

        delete_entry_with_id(Input, input_id)
        try:
            display_order = csv_to_list_of_str(
                DisplayOrder.query.first().inputs)
            display_order.remove(input_id)
            DisplayOrder.query.first().inputs = list_to_csv(display_order)
        except Exception:  # id not in list
            pass
        db.session.commit()
    except Exception as except_msg:
        error.append(except_msg)

    flash_success_errors(error, action, url_for('routes_page.page_data'))
Exemple #5
0
def output_del(form_output):
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['delete']['title'],
        controller=TRANSLATIONS['output']['title'])
    error = []

    try:
        device_measurements = DeviceMeasurements.query.filter(
            DeviceMeasurements.device_id == form_output.output_id.data).all()

        for each_measurement in device_measurements:
            delete_entry_with_id(DeviceMeasurements,
                                 each_measurement.unique_id)

        delete_entry_with_id(Output, form_output.output_id.data)

        display_order = csv_to_list_of_str(DisplayOrder.query.first().output)
        display_order.remove(form_output.output_id.data)
        DisplayOrder.query.first().output = list_to_csv(display_order)
        db.session.commit()

        manipulate_output('Delete', form_output.output_id.data)
    except Exception as except_msg:
        error.append(except_msg)
    flash_success_errors(error, action, url_for('routes_page.page_output'))
Exemple #6
0
def function_del(function_id):
    """Delete a Function"""
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['delete']['title'],
        controller=TRANSLATIONS['function']['title'])
    error = []

    try:
        # Delete Actions
        actions = Actions.query.filter(
            Actions.function_id == function_id).all()
        for each_action in actions:
            delete_entry_with_id(Actions,
                                 each_action.unique_id)

        delete_entry_with_id(Function, function_id)

        display_order = csv_to_list_of_str(DisplayOrder.query.first().function)
        display_order.remove(function_id)
        DisplayOrder.query.first().function = list_to_csv(display_order)
        db.session.commit()
    except Exception as except_msg:
        error.append(except_msg)

    flash_success_errors(error, action, url_for('routes_page.page_function'))
Exemple #7
0
def math_del(form_mod_math):
    action = '{action} {controller}'.format(
        action=gettext("Delete"),
        controller=gettext("Math"))
    error = []

    try:
        math = Math.query.filter(
            Math.unique_id == form_mod_math.math_id.data).first()
        if math.is_activated:
            controller_activate_deactivate(
                'deactivate',
                'Math',
                form_mod_math.math_id.data)

        delete_entry_with_id(Math, form_mod_math.math_id.data)
        try:
            display_order = csv_to_list_of_str(DisplayOrder.query.first().math)
            display_order.remove(form_mod_math.math_id.data)
            DisplayOrder.query.first().math = list_to_csv(display_order)
        except Exception:  # id not in list
            pass
        db.session.commit()
    except Exception as except_msg:
        error.append(except_msg)

    flash_success_errors(error, action, url_for('routes_page.page_data'))
Exemple #8
0
def lcd_del(lcd_id):
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['delete']['title'],
        controller=TRANSLATIONS['lcd']['title'])
    error = []

    lcd = LCD.query.filter(LCD.unique_id == lcd_id).first()
    if lcd.is_activated:
        error.append(
            gettext(
                "Deactivate LCD controller before modifying its settings."))

    if not error:
        try:
            # Delete all LCD Displays
            lcd_displays = LCDData.query.filter(LCDData.lcd_id == lcd_id).all()
            for each_lcd_display in lcd_displays:
                lcd_display_del(each_lcd_display.unique_id, delete_last=True)

            # Delete LCD
            delete_entry_with_id(LCD, lcd_id)
            display_order = csv_to_list_of_str(DisplayOrder.query.first().lcd)
            display_order.remove(lcd_id)
            DisplayOrder.query.first().lcd = list_to_csv(display_order)
            db.session.commit()
        except Exception as except_msg:
            error.append(except_msg)
    flash_success_errors(error, action, url_for('routes_page.page_lcd'))
Exemple #9
0
def output_add(form_add):
    action = '{action} {controller}'.format(action=gettext("Add"),
                                            controller=gettext("Output"))
    error = []

    dep_unmet, _ = return_dependencies(form_add.output_type.data)
    if dep_unmet:
        list_unmet_deps = []
        for each_dep in dep_unmet:
            list_unmet_deps.append(each_dep[0])
        error.append(
            "The {dev} device you're trying to add has unmet dependencies: {dep}"
            .format(dev=form_add.output_type.data,
                    dep=', '.join(list_unmet_deps)))

    if is_int(form_add.output_quantity.data, check_range=[1, 20]):
        for _ in range(0, form_add.output_quantity.data):
            try:
                new_output = Output()
                new_output.name = OUTPUT_INFO[
                    form_add.output_type.data]['name']
                new_output.output_type = form_add.output_type.data
                if form_add.output_type.data == 'wired':
                    new_output.on_at_start = False
                elif form_add.output_type.data == 'wireless_433MHz_pi_switch':
                    new_output.pin = None
                    new_output.protocol = 1
                    new_output.pulse_length = 189
                    new_output.on_command = '22559'
                    new_output.off_command = '22558'
                elif form_add.output_type.data == 'command':
                    new_output.on_command = '/home/pi/script_on.sh'
                    new_output.off_command = '/home/pi/script_off.sh'
                elif form_add.output_type.data == 'command_pwm':
                    new_output.pwm_command = '/home/pi/script_pwm.sh ((duty_cycle))'
                elif form_add.output_type.data == 'pwm':
                    new_output.pwm_hertz = 22000
                    new_output.pwm_library = 'pigpio_any'

                if not error:
                    new_output.save()
                    display_order = csv_to_list_of_str(
                        DisplayOrder.query.first().output)
                    DisplayOrder.query.first().output = add_display_order(
                        display_order, new_output.unique_id)
                    db.session.commit()
                    manipulate_output('Add', new_output.unique_id)
            except sqlalchemy.exc.OperationalError as except_msg:
                error.append(except_msg)
            except sqlalchemy.exc.IntegrityError as except_msg:
                error.append(except_msg)
    else:
        error_msg = "{error}. {accepted_values}: 1-20".format(
            error=gettext("Invalid quantity"),
            accepted_values=gettext("Acceptable values"))
        error.append(error_msg)
    flash_success_errors(error, action, url_for('routes_page.page_output'))

    if dep_unmet:
        return 1
Exemple #10
0
def lcd_add(form):
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['add']['title'],
        controller=TRANSLATIONS['lcd']['title'])
    error = []

    if current_app.config['TESTING']:
        dep_unmet = False
    else:
        dep_unmet, _ = return_dependencies(form.lcd_type.data)
        if dep_unmet:
            list_unmet_deps = []
            for each_dep in dep_unmet:
                list_unmet_deps.append(each_dep[0])
            error.append("The {dev} device you're trying to add has unmet dependencies: {dep}".format(
                dev=form.lcd_type.data, dep=', '.join(list_unmet_deps)))

    try:
        new_lcd = LCD()
        new_lcd_data = LCDData()
        if GPIO.RPI_REVISION == 2 or GPIO.RPI_REVISION == 3:
            new_lcd.i2c_bus = 1
        else:
            new_lcd.i2c_bus = 0
        new_lcd.lcd_type = form.lcd_type.data
        new_lcd.name = str(LCD_INFO[form.lcd_type.data]['name'])

        if form.lcd_type.data == '128x32_pioled':
            new_lcd.location = '0x3c'
            new_lcd.x_characters = 21
            new_lcd.y_lines = 4
        elif form.lcd_type.data == '128x64_pioled':
            new_lcd.location = '0x3c'
            new_lcd.x_characters = 21
            new_lcd.y_lines = 8
        elif form.lcd_type.data == '16x2_generic':
            new_lcd.location = '0x27'
            new_lcd.x_characters = 16
            new_lcd.y_lines = 2
        elif form.lcd_type.data == '16x4_generic':
            new_lcd.location = '0x27'
            new_lcd.x_characters = 16
            new_lcd.y_lines = 4

        if not error:
            new_lcd.save()
            new_lcd_data.lcd_id = new_lcd.unique_id
            new_lcd_data.save()
            display_order = csv_to_list_of_str(DisplayOrder.query.first().lcd)
            DisplayOrder.query.first().lcd = add_display_order(
                display_order, new_lcd.unique_id)
            db.session.commit()
    except sqlalchemy.exc.OperationalError as except_msg:
        error.append(except_msg)
    except sqlalchemy.exc.IntegrityError as except_msg:
        error.append(except_msg)
    flash_success_errors(error, action, url_for('routes_page.page_lcd'))

    if dep_unmet:
        return 1
Exemple #11
0
def math_del(form_mod_math):
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['delete']['title'],
        controller=TRANSLATIONS['math']['title'])
    error = []

    math_id = form_mod_math.math_id.data

    try:
        math = Math.query.filter(
            Math.unique_id == math_id).first()
        if math.is_activated:
            controller_activate_deactivate(
                'deactivate',
                'Math',
                form_mod_math.math_id.data)

        device_measurements = DeviceMeasurements.query.filter(
            DeviceMeasurements.device_id == math_id).all()

        for each_measurement in device_measurements:
            delete_entry_with_id(DeviceMeasurements, each_measurement.unique_id)

        delete_entry_with_id(Math, math_id)
        try:
            display_order = csv_to_list_of_str(DisplayOrder.query.first().math)
            display_order.remove(math_id)
            DisplayOrder.query.first().math = list_to_csv(display_order)
        except Exception:  # id not in list
            pass
        db.session.commit()
    except Exception as except_msg:
        error.append(except_msg)

    flash_success_errors(error, action, url_for('routes_page.page_data'))
Exemple #12
0
def pid_del(pid_id):
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['delete']['title'],
        controller=TRANSLATIONS['pid']['title'])
    error = []

    try:
        pid = PID.query.filter(
            PID.unique_id == pid_id).first()
        if pid.is_activated:
            pid_deactivate(pid_id)

        device_measurements = DeviceMeasurements.query.filter(
            DeviceMeasurements.device_id == pid_id).all()

        for each_measurement in device_measurements:
            delete_entry_with_id(DeviceMeasurements, each_measurement.unique_id)

        delete_entry_with_id(PID, pid_id)
        try:
            display_order = csv_to_list_of_str(DisplayOrder.query.first().math)
            display_order.remove(pid_id)
            DisplayOrder.query.first().function = list_to_csv(display_order)
        except Exception:  # id not in list
            pass
        db.session.commit()
    except Exception as except_msg:
        error.append(except_msg)

    flash_success_errors(error, action, url_for('routes_page.page_function'))
Exemple #13
0
def input_del(form_mod):
    action = '{action} {controller}'.format(
        action=gettext("Delete"),
        controller=gettext("Input"))
    error = []

    input_id = form_mod.input_id.data

    try:
        input_dev = Input.query.filter(
            Input.unique_id == input_id).first()
        if input_dev.is_activated:
            input_deactivate_associated_controllers(input_id)
            controller_activate_deactivate('deactivate', 'Input', input_id)

        delete_entry_with_id(Input, input_id)
        try:
            display_order = csv_to_list_of_str(
                DisplayOrder.query.first().inputs)
            display_order.remove(input_id)
            DisplayOrder.query.first().inputs = list_to_csv(display_order)
        except Exception:  # id not in list
            pass
        db.session.commit()
    except Exception as except_msg:
        error.append(except_msg)

    flash_success_errors(error, action, url_for('routes_page.page_data'))
Exemple #14
0
def math_add(form_add_math):
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['add']['title'],
        controller=TRANSLATIONS['math']['title'])
    error = []

    dep_unmet, _ = return_dependencies(form_add_math.math_type.data)
    if dep_unmet:
        list_unmet_deps = []
        for each_dep in dep_unmet:
            list_unmet_deps.append(each_dep[0])
        error.append("The {dev} device you're trying to add has unmet dependencies: {dep}".format(
            dev=form_add_math.math_type.data, dep=', '.join(list_unmet_deps)))

    if form_add_math.validate():
        new_math = Math()
        new_math.name = str(MATH_INFO[form_add_math.math_type.data]['name'])
        new_math.math_type = form_add_math.math_type.data

        try:
            new_math.save()

            display_order = csv_to_list_of_str(
                DisplayOrder.query.first().math)
            DisplayOrder.query.first().math = add_display_order(
                display_order, new_math.unique_id)
            db.session.commit()

            if not MATH_INFO[form_add_math.math_type.data]['measure']:
                new_measurement = DeviceMeasurements()
                new_measurement.device_id = new_math.unique_id
                new_measurement.channel = 0
                new_measurement.save()
            else:
                for each_channel, measure_info in MATH_INFO[form_add_math.math_type.data]['measure'].items():
                    new_measurement = DeviceMeasurements()
                    if 'name' in measure_info and measure_info['name']:
                        new_measurement.name = measure_info['name']
                    new_measurement.device_id = new_math.unique_id
                    new_measurement.measurement = measure_info['measurement']
                    new_measurement.unit = measure_info['unit']
                    new_measurement.channel = each_channel
                    new_measurement.save()

            flash(gettext(
                "%(type)s Math with ID %(id)s (%(uuid)s) successfully added",
                type=form_add_math.math_type.data,
                id=new_math.id,
                uuid=new_math.unique_id),
                  "success")
        except sqlalchemy.exc.OperationalError as except_msg:
            error.append(except_msg)
        except sqlalchemy.exc.IntegrityError as except_msg:
            error.append(except_msg)
        flash_success_errors(error, action, url_for('routes_page.page_data'))
    else:
        flash_form_errors(form_add_math)

    if dep_unmet:
        return 1
Exemple #15
0
def function_del(function_id):
    """Delete a Function"""
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['delete']['title'],
        controller=TRANSLATIONS['function']['title'])
    error = []

    try:
        # Delete Actions
        actions = Actions.query.filter(
            Actions.function_id == function_id).all()
        for each_action in actions:
            delete_entry_with_id(Actions, each_action.unique_id)

        device_measurements = DeviceMeasurements.query.filter(
            DeviceMeasurements.device_id == function_id).all()
        for each_measurement in device_measurements:
            delete_entry_with_id(DeviceMeasurements, each_measurement.unique_id)

        delete_entry_with_id(Function, function_id)

        display_order = csv_to_list_of_str(DisplayOrder.query.first().function)
        display_order.remove(function_id)
        DisplayOrder.query.first().function = list_to_csv(display_order)
        db.session.commit()
    except Exception as except_msg:
        error.append(except_msg)

    flash_success_errors(error, action, url_for('routes_page.page_function'))
def method_delete(method_id):
    """Delete a method"""
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['delete']['title'],
        controller=gettext("Method"))

    if not utils_general.user_has_permission('edit_settings'):
        return redirect(url_for('routes_method.method_list'))

    try:
        MethodData.query.filter(
            MethodData.method_id == method_id).delete()
        MethodData.query.filter(
            MethodData.linked_method_id == method_id).delete()
        Method.query.filter(
            Method.unique_id == method_id).delete()
        display_order = csv_to_list_of_str(DisplayOrder.query.first().method)
        display_order.remove(method_id)
        DisplayOrder.query.first().method = list_to_csv(display_order)
        db.session.commit()
        flash("Success: {action}".format(action=action), "success")
    except Exception as except_msg:
        flash("Error: {action}: {err}".format(action=action,
                                              err=except_msg),
              "error")
    return redirect(url_for('routes_method.method_list'))
Exemple #17
0
def lcd_add(quantity):
    action = '{action} {controller}'.format(
        action=gettext("Add"),
        controller=gettext("LCD"))
    error = []
    for _ in range(0, quantity):
        try:
            new_lcd = LCD()
            new_lcd_data = LCDData()
            if GPIO.RPI_REVISION == 2 or GPIO.RPI_REVISION == 3:
                new_lcd.i2c_bus = 1
            else:
                new_lcd.i2c_bus = 0
            new_lcd.save()
            new_lcd_data.lcd_id = new_lcd.unique_id
            new_lcd_data.save()
            display_order = csv_to_list_of_str(DisplayOrder.query.first().lcd)
            DisplayOrder.query.first().lcd = add_display_order(
                display_order, new_lcd.unique_id)
            db.session.commit()
        except sqlalchemy.exc.OperationalError as except_msg:
            error.append(except_msg)
        except sqlalchemy.exc.IntegrityError as except_msg:
            error.append(except_msg)
        flash_success_errors(error, action, url_for('routes_page.page_lcd'))
Exemple #18
0
def lcd_del(lcd_id):
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['delete']['title'],
        controller=TRANSLATIONS['lcd']['title'])
    error = []

    lcd = LCD.query.filter(
        LCD.unique_id == lcd_id).first()
    if lcd.is_activated:
        error.append(gettext("Deactivate LCD controller before modifying "
                             "its settings."))

    if not error:
        try:
            # Delete all LCD Displays
            lcd_displays = LCDData.query.filter(
                LCDData.lcd_id == lcd_id).all()
            for each_lcd_display in lcd_displays:
                lcd_display_del(each_lcd_display.unique_id, delete_last=True)

            # Delete LCD
            delete_entry_with_id(LCD, lcd_id)
            display_order = csv_to_list_of_str(DisplayOrder.query.first().lcd)
            display_order.remove(lcd_id)
            DisplayOrder.query.first().lcd = list_to_csv(display_order)
            db.session.commit()
        except Exception as except_msg:
            error.append(except_msg)
    flash_success_errors(error, action, url_for('routes_page.page_lcd'))
Exemple #19
0
def conditional_del(cond_id):
    """Delete a Conditional"""
    error = []
    action = '{action} {controller}'.format(
        action=gettext("Delete"),
        controller=gettext("Conditional"))

    cond = Conditional.query.filter(
        Conditional.unique_id == cond_id).first()

    # Deactivate conditional if active
    if cond.is_activated:
        conditional_deactivate(cond_id)

    try:
        if not error:
            # Delete conditional
            conditional_actions = ConditionalActions.query.filter(
                ConditionalActions.conditional_id == cond.unique_id).all()
            for each_cond_action in conditional_actions:
                delete_entry_with_id(ConditionalActions,
                                     each_cond_action.unique_id)
            delete_entry_with_id(Conditional, cond.unique_id)

            display_order = csv_to_list_of_str(
                DisplayOrder.query.first().conditional)

            try:
                display_order.remove(cond.unique_id)
                DisplayOrder.query.first().conditional = list_to_csv(
                    display_order)
            except Exception:  # id not in list
                pass

            db.session.commit()

            # Check display order for conditional IDs that don't exist
            # Delete any non-existent IDs from order list
            fixed_display_order = display_order
            fixed = False
            for each_id in display_order:
                if not Conditional.query.filter(
                        Conditional.unique_id == each_id).count():
                    fixed = True
                    fixed_display_order.remove(each_id)
            if fixed:
                DisplayOrder.query.first().conditional = list_to_csv(
                    fixed_display_order)
                db.session.commit()

    except sqlalchemy.exc.OperationalError as except_msg:
        error.append(except_msg)
    except sqlalchemy.exc.IntegrityError as except_msg:
        error.append(except_msg)
    except Exception as except_msg:
        error.append(except_msg)

    flash_success_errors(error, action, url_for('routes_page.page_function'))
def conditional_del(cond_id):
    """Delete a Conditional"""
    error = []
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['delete']['title'],
        controller=TRANSLATIONS['conditional']['title'])

    cond = Conditional.query.filter(
        Conditional.unique_id == cond_id).first()

    # Deactivate conditional if active
    if cond.is_activated:
        conditional_deactivate(cond_id)

    try:
        if not error:
            # Delete conditions
            conditions = ConditionalConditions.query.filter(
                ConditionalConditions.conditional_id == cond_id).all()
            for each_condition in conditions:
                delete_entry_with_id(ConditionalConditions,
                                     each_condition.unique_id)

            # Delete Actions
            actions = Actions.query.filter(
                Actions.function_id == cond_id).all()
            for each_action in actions:
                delete_entry_with_id(Actions,
                                     each_action.unique_id)

            delete_entry_with_id(Conditional, cond_id)

            display_order = csv_to_list_of_str(DisplayOrder.query.first().function)
            display_order.remove(cond_id)
            DisplayOrder.query.first().function = list_to_csv(display_order)

            try:
                file_path = os.path.join(
                    PATH_PYTHON_CODE_USER, 'conditional_{}.py'.format(
                        cond.unique_id))
                os.remove(file_path)
            except:
                pass

            db.session.commit()
    except sqlalchemy.exc.OperationalError as except_msg:
        error.append(except_msg)
    except sqlalchemy.exc.IntegrityError as except_msg:
        error.append(except_msg)
    except Exception as except_msg:
        error.append(except_msg)

    flash_success_errors(error, action, url_for('routes_page.page_function'))
Exemple #21
0
def controller_del(cond_id):
    """Delete a Conditional"""
    error = []
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['delete']['title'],
        controller=TRANSLATIONS['controller']['title'])

    cond = CustomController.query.filter(
        CustomController.unique_id == cond_id).first()

    # Deactivate controller if active
    if cond.is_activated:
        controller_deactivate(cond_id)

    try:
        if not error:
            device_measurements = DeviceMeasurements.query.filter(
                DeviceMeasurements.device_id == cond_id).all()
            for each_measurement in device_measurements:
                delete_entry_with_id(DeviceMeasurements,
                                     each_measurement.unique_id)

            delete_entry_with_id(CustomController, cond_id)

            channels = FunctionChannel.query.filter(
                FunctionChannel.function_id == cond_id).all()
            for each_channel in channels:
                delete_entry_with_id(FunctionChannel, each_channel.unique_id)

            display_order = csv_to_list_of_str(
                DisplayOrder.query.first().function)
            display_order.remove(cond_id)
            DisplayOrder.query.first().function = list_to_csv(display_order)

            try:
                file_path = os.path.join(
                    PATH_PYTHON_CODE_USER,
                    'conditional_{}.py'.format(cond.unique_id))
                os.remove(file_path)
            except:
                pass

            db.session.commit()
    except sqlalchemy.exc.OperationalError as except_msg:
        error.append(except_msg)
    except sqlalchemy.exc.IntegrityError as except_msg:
        error.append(except_msg)
    except Exception as except_msg:
        error.append(except_msg)

    flash_success_errors(error, action, url_for('routes_page.page_function'))
Exemple #22
0
def input_del(input_id):
    messages = {"success": [], "info": [], "warning": [], "error": []}

    try:
        input_dev = Input.query.filter(Input.unique_id == input_id).first()

        if input_dev.is_activated:
            input_deactivate_associated_controllers(input_id)
            controller_activate_deactivate('deactivate', 'Input', input_id)

        device_measurements = DeviceMeasurements.query.filter(
            DeviceMeasurements.device_id == input_id).all()

        for each_measurement in device_measurements:
            delete_entry_with_id(DeviceMeasurements,
                                 each_measurement.unique_id,
                                 flash_message=False)

        delete_entry_with_id(Input, input_id, flash_message=False)

        channels = InputChannel.query.filter(
            InputChannel.input_id == input_id).all()
        for each_channel in channels:
            delete_entry_with_id(InputChannel,
                                 each_channel.unique_id,
                                 flash_message=False)

        try:
            display_order = csv_to_list_of_str(
                DisplayOrder.query.first().inputs)
            display_order.remove(input_id)
            DisplayOrder.query.first().inputs = list_to_csv(display_order)
        except Exception:  # id not in list
            pass

        try:
            file_path = os.path.join(
                PATH_PYTHON_CODE_USER,
                'input_python_code_{}.py'.format(input_dev.unique_id))
            os.remove(file_path)
        except:
            pass

        db.session.commit()
        messages["success"].append('{action} {controller}'.format(
            action=TRANSLATIONS['delete']['title'],
            controller=TRANSLATIONS['input']['title']))
    except Exception as except_msg:
        messages["error"].append(str(except_msg))

    return messages
Exemple #23
0
def output_del(form_output):
    action = '{action} {controller}'.format(action=gettext("Delete"),
                                            controller=gettext("Output"))
    error = []

    try:
        delete_entry_with_id(Output, form_output.output_id.data)
        display_order = csv_to_list_of_str(DisplayOrder.query.first().output)
        display_order.remove(form_output.output_id.data)
        DisplayOrder.query.first().output = list_to_csv(display_order)
        db.session.commit()
        manipulate_output('Delete', form_output.output_id.data)
    except Exception as except_msg:
        error.append(except_msg)
    flash_success_errors(error, action, url_for('routes_page.page_output'))
Exemple #24
0
def dashboard_del(form_base):
    """Delete an item on the dashboard"""
    action = '{action} {controller}'.format(action=gettext("Delete"),
                                            controller=gettext("Dashboard"))
    error = []

    try:
        delete_entry_with_id(Dashboard, form_base.dashboard_id.data)
        display_order = csv_to_list_of_str(
            DisplayOrder.query.first().dashboard)
        display_order.remove(form_base.dashboard_id.data)
        DisplayOrder.query.first().dashboard = list_to_csv(display_order)
        db.session.commit()
    except Exception as except_msg:
        error.append(except_msg)
    flash_success_errors(error, action, url_for('routes_page.page_dashboard'))
def remote_host_del(form_setup):
    """Delete a remote Mycodo from the Remote Admin Dashboard"""
    if not utils_general.user_has_permission('edit_settings'):
        return redirect(url_for('routes_general.home'))

    try:
        delete_entry_with_id(Remote,
                             form_setup.remote_id.data)
        display_order = csv_to_list_of_str(
            DisplayOrder.query.first().remote_host)
        display_order.remove(form_setup.remote_id.data)
        DisplayOrder.query.first().remote_host = list_to_csv(display_order)
        db.session.commit()
    except Exception as except_msg:
        flash(gettext("Error: %(err)s",
                      err='Remote Host Delete: {msg}'.format(msg=except_msg)),
              "error")
Exemple #26
0
def output_del(form_output):
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['delete']['title'],
        controller=TRANSLATIONS['output']['title'])
    error = []

    try:
        delete_entry_with_id(Output,
                             form_output.output_id.data)
        display_order = csv_to_list_of_str(DisplayOrder.query.first().output)
        display_order.remove(form_output.output_id.data)
        DisplayOrder.query.first().output = list_to_csv(display_order)
        db.session.commit()
        manipulate_output('Delete', form_output.output_id.data)
    except Exception as except_msg:
        error.append(except_msg)
    flash_success_errors(error, action, url_for('routes_page.page_output'))
Exemple #27
0
def dashboard_del(form_base):
    """Delete an item on the dashboard"""
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['delete']['title'],
        controller=TRANSLATIONS['dashboard']['title'])
    error = []

    try:
        delete_entry_with_id(Dashboard,
                             form_base.dashboard_id.data)
        display_order = csv_to_list_of_str(DisplayOrder.query.first().dashboard)
        display_order.remove(form_base.dashboard_id.data)
        DisplayOrder.query.first().dashboard = list_to_csv(display_order)
        db.session.commit()
    except Exception as except_msg:
        error.append(except_msg)
    flash_success_errors(error, action, url_for('routes_page.page_dashboard'))
Exemple #28
0
def math_add(form_add_math):
    action = '{action} {controller}'.format(
        action=gettext("Add"),
        controller=gettext("Math"))
    error = []

    unmet_deps = return_dependencies(form_add_math.math_type.data)
    if unmet_deps:
        error.append("The {dev} device you're trying to add has unmet dependencies: {dep}".format(
            dev=form_add_math.math_type.data, dep=unmet_deps))

    if form_add_math.validate():
        new_math = Math()
        new_math.name = ''
        new_math.math_type = form_add_math.math_type.data

        if form_add_math.math_type.data in MATH_INFO:
            new_math.name += '{name}'.format(name=MATH_INFO[form_add_math.math_type.data]['name'])
            new_math.measure = ",".join(MATH_INFO[form_add_math.math_type.data]['measure'])

        try:
            new_math.save()

            display_order = csv_to_list_of_str(
                DisplayOrder.query.first().math)
            DisplayOrder.query.first().math = add_display_order(
                display_order, new_math.unique_id)
            db.session.commit()

            flash(gettext(
                "%(type)s Math with ID %(id)s (%(uuid)s) successfully added",
                type=form_add_math.math_type.data,
                id=new_math.id,
                uuid=new_math.unique_id),
                  "success")
        except sqlalchemy.exc.OperationalError as except_msg:
            error.append(except_msg)
        except sqlalchemy.exc.IntegrityError as except_msg:
            error.append(except_msg)
        flash_success_errors(error, action, url_for('routes_page.page_data'))
    else:
        flash_form_errors(form_add_math)

    if unmet_deps:
        return 1
def conditional_del(cond_id):
    """Delete a Conditional"""
    error = []
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['delete']['title'],
        controller=TRANSLATIONS['conditional']['title'])

    cond = Conditional.query.filter(
        Conditional.unique_id == cond_id).first()

    # Deactivate conditional if active
    if cond.is_activated:
        conditional_deactivate(cond_id)

    try:
        if not error:
            # Delete conditions
            conditions = ConditionalConditions.query.filter(
                ConditionalConditions.conditional_id == cond_id).all()
            for each_condition in conditions:
                delete_entry_with_id(ConditionalConditions,
                                     each_condition.unique_id)

            # Delete Actions
            actions = Actions.query.filter(
                Actions.function_id == cond_id).all()
            for each_action in actions:
                delete_entry_with_id(Actions,
                                     each_action.unique_id)

            delete_entry_with_id(Conditional, cond_id)

            display_order = csv_to_list_of_str(DisplayOrder.query.first().function)
            display_order.remove(cond_id)
            DisplayOrder.query.first().function = list_to_csv(display_order)
            db.session.commit()
    except sqlalchemy.exc.OperationalError as except_msg:
        error.append(except_msg)
    except sqlalchemy.exc.IntegrityError as except_msg:
        error.append(except_msg)
    except Exception as except_msg:
        error.append(except_msg)

    flash_success_errors(error, action, url_for('routes_page.page_function'))
Exemple #30
0
def pid_del(pid_id):
    action = '{action} {controller}'.format(action=gettext("Delete"),
                                            controller=gettext("PID"))
    error = []

    try:
        pid = PID.query.filter(PID.unique_id == pid_id).first()
        if pid.is_activated:
            pid_deactivate(pid_id)

        delete_entry_with_id(PID, pid_id)

        display_order = csv_to_list_of_str(DisplayOrder.query.first().pid)
        display_order.remove(pid_id)
        DisplayOrder.query.first().pid = list_to_csv(display_order)
        db.session.commit()
    except Exception as except_msg:
        error.append(except_msg)

    flash_success_errors(error, action, url_for('routes_page.page_function'))
Exemple #31
0
def output_del(form_output):
    messages = {"success": [], "info": [], "warning": [], "error": []}

    try:
        device_measurements = DeviceMeasurements.query.filter(
            DeviceMeasurements.device_id == form_output.output_id.data).all()

        for each_measurement in device_measurements:
            delete_entry_with_id(DeviceMeasurements,
                                 each_measurement.unique_id,
                                 flash_message=False)

        delete_entry_with_id(Output,
                             form_output.output_id.data,
                             flash_message=False)

        channels = OutputChannel.query.filter(
            OutputChannel.output_id == form_output.output_id.data).all()
        for each_channel in channels:
            delete_entry_with_id(OutputChannel,
                                 each_channel.unique_id,
                                 flash_message=False)

        display_order = csv_to_list_of_str(DisplayOrder.query.first().output)
        display_order.remove(form_output.output_id.data)
        DisplayOrder.query.first().output = list_to_csv(display_order)
        db.session.commit()
        messages["success"].append('{action} {controller}'.format(
            action=TRANSLATIONS['delete']['title'],
            controller=TRANSLATIONS['output']['title']))

        if not current_app.config['TESTING']:
            new_messages = manipulate_output('Delete',
                                             form_output.output_id.data)
            messages["error"].extend(new_messages["error"])
            messages["success"].extend(new_messages["success"])
    except Exception as except_msg:
        messages["error"].append(except_msg)

    return messages
Exemple #32
0
def trigger_del(trigger_id):
    """Delete a Trigger"""
    error = []
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['delete']['title'],
        controller=TRANSLATIONS['trigger']['title'])

    trigger = Trigger.query.filter(
        Trigger.unique_id == trigger_id).first()

    # Deactivate trigger if active
    if trigger.is_activated:
        trigger_deactivate(trigger_id)

    try:
        if not error:
            # Delete Actions
            actions = Actions.query.filter(
                Actions.function_id == trigger_id).all()
            for each_action in actions:
                delete_entry_with_id(Actions,
                                     each_action.unique_id)

            delete_entry_with_id(Trigger, trigger_id)

            display_order = csv_to_list_of_str(DisplayOrder.query.first().function)
            display_order.remove(trigger_id)
            DisplayOrder.query.first().function = list_to_csv(display_order)
            db.session.commit()
    except sqlalchemy.exc.OperationalError as except_msg:
        error.append(except_msg)
    except sqlalchemy.exc.IntegrityError as except_msg:
        error.append(except_msg)
    except Exception as except_msg:
        error.append(except_msg)

    flash_success_errors(error, action, url_for('routes_page.page_function'))
Exemple #33
0
def output_add(form_add):
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['add']['title'],
        controller=TRANSLATIONS['output']['title'])
    error = []

    dep_unmet, _ = return_dependencies(form_add.output_type.data.split(',')[0])
    if dep_unmet:
        list_unmet_deps = []
        for each_dep in dep_unmet:
            list_unmet_deps.append(each_dep[0])
        error.append(
            "The {dev} device you're trying to add has unmet dependencies: "
            "{dep}".format(dev=form_add.output_type.data,
                           dep=', '.join(list_unmet_deps)))

    if len(form_add.output_type.data.split(',')) < 2:
        error.append("Must select an Output type")

    if not is_int(form_add.output_quantity.data, check_range=[1, 20]):
        error.append("{error}. {accepted_values}: 1-20".format(
            error=gettext("Invalid quantity"),
            accepted_values=gettext("Acceptable values")))

    if not error:
        for _ in range(0, form_add.output_quantity.data):
            try:
                output_type = form_add.output_type.data.split(',')[0]
                interface = form_add.output_type.data.split(',')[1]

                new_output = Output()
                new_output.name = str(OUTPUT_INFO[output_type]['name'])
                new_output.output_type = output_type
                new_output.interface = interface

                if output_type in [
                        'wired', 'wireless_rpi_rf', 'command', 'python'
                ]:
                    new_output.measurement = 'duration_time'
                    new_output.unit = 's'

                elif output_type in OUTPUTS_PWM:
                    new_output.measurement = 'duty_cycle'
                    new_output.unit = 'percent'

                new_output.channel = 0

                if output_type == 'wired':
                    new_output.state_startup = '0'
                    new_output.state_shutdown = '0'

                elif output_type == 'wireless_rpi_rf':
                    new_output.pin = None
                    new_output.protocol = 1
                    new_output.pulse_length = 189
                    new_output.on_command = '22559'
                    new_output.off_command = '22558'

                elif output_type == 'command':
                    new_output.on_command = '/home/pi/script_on.sh'
                    new_output.off_command = '/home/pi/script_off.sh'

                elif output_type == 'command_pwm':
                    new_output.pwm_command = '/home/pi/script_pwm.sh ((duty_cycle))'

                elif output_type == 'pwm':
                    new_output.pwm_hertz = 22000
                    new_output.pwm_library = 'pigpio_any'

                elif output_type == 'python':
                    new_output.on_command = """
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
write_string = "{ts}: ID: {id}: ON\\n".format(id=output_id, ts=timestamp)
with open("/home/pi/Mycodo/OutputTest.txt", "a") as myfile:
    myfile.write(write_string)"""
                    new_output.off_command = """
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
write_string = "{ts}: ID: {id}: OFF\\n".format(id=output_id, ts=timestamp)
with open("/home/pi/Mycodo/OutputTest.txt", "a") as myfile:
    myfile.write(write_string)"""

                elif output_type == 'python_pwm':
                    new_output.pwm_command = """
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
write_string = "{ts}: ID: {id}: Duty Cycle: ((duty_cycle)) %\\n".format(
    id=output_id, ts=timestamp)
with open("/home/pi/Mycodo/OutputTest.txt", "a") as myfile:
    myfile.write(write_string)"""

                elif output_type == 'atlas_ezo_pmp':
                    new_output.output_mode = 'fastest_flow_rate'
                    new_output.flow_rate = 10
                    if interface == 'FTDI':
                        new_output.location = '/dev/ttyUSB0'
                    elif interface == 'I2C':
                        new_output.location = '0x67'
                        new_output.i2c_bus = 1
                    elif interface == 'UART':
                        new_output.location = '/dev/ttyAMA0'
                        new_output.baud_rate = 9600

                if not error:
                    new_output.save()
                    display_order = csv_to_list_of_str(
                        DisplayOrder.query.first().output)
                    DisplayOrder.query.first().output = add_display_order(
                        display_order, new_output.unique_id)
                    db.session.commit()

                    # Add device measurements
                    for measurement, measure_data in OUTPUT_INFO[
                            new_output.output_type]['measure'].items():
                        for unit, unit_data in measure_data.items():
                            for channel, _ in unit_data.items():
                                new_measurement = DeviceMeasurements()
                                new_measurement.device_id = new_output.unique_id
                                new_measurement.name = ''
                                new_measurement.is_enabled = True
                                new_measurement.measurement = measurement
                                new_measurement.unit = unit
                                new_measurement.channel = channel
                                new_measurement.save()

                    manipulate_output('Add', new_output.unique_id)
            except sqlalchemy.exc.OperationalError as except_msg:
                error.append(except_msg)
            except sqlalchemy.exc.IntegrityError as except_msg:
                error.append(except_msg)

    flash_success_errors(error, action, url_for('routes_page.page_output'))

    if dep_unmet:
        return 1
Exemple #34
0
def input_add(form_add):
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['add']['title'],
        controller=TRANSLATIONS['input']['title'])
    error = []

    dict_inputs = parse_input_information()

    # only one comma should be in the input_type string
    if form_add.input_type.data.count(',') > 1:
        error.append("Invalid input module formatting. It appears there is "
                     "a comma in either 'input_name_unique' or 'interfaces'.")

    if form_add.input_type.data.count(',') == 1:
        input_name = form_add.input_type.data.split(',')[0]
        input_interface = form_add.input_type.data.split(',')[1]
    else:
        input_name = ''
        input_interface = ''
        error.append("Invalid input string (must be a comma-separated string)")

    if current_app.config['TESTING']:
        dep_unmet = False
    else:
        dep_unmet, _ = return_dependencies(input_name)
        if dep_unmet:
            list_unmet_deps = []
            for each_dep in dep_unmet:
                list_unmet_deps.append(each_dep[0])
            error.append("The {dev} device you're trying to add has unmet dependencies: {dep}".format(
                dev=input_name, dep=', '.join(list_unmet_deps)))

    if form_add.validate():
        new_input = Input()
        new_input.device = input_name

        if input_interface:
            new_input.interface = input_interface

        if GPIO.RPI_INFO['P1_REVISION'] in [2, 3]:
            new_input.i2c_bus = 1
        else:
            new_input.i2c_bus = 0

        if 'input_name' in dict_inputs[input_name]:
            new_input.name = dict_inputs[input_name]['input_name']
        else:
            new_input.name = 'Input Name'

        #
        # Set default values for new input being added
        #

        # input add options
        if input_name in dict_inputs:
            def dict_has_value(key):
                if (key in dict_inputs[input_name] and
                        (dict_inputs[input_name][key] or dict_inputs[input_name][key] == 0)):
                    return True

            #
            # Interfacing options
            #

            # I2C options
            if input_interface == 'I2C':
                if dict_has_value('i2c_location'):
                    new_input.i2c_location = dict_inputs[input_name]['i2c_location'][0]  # First entry in list

            # UART options
            if dict_has_value('uart_location'):
                new_input.uart_location = dict_inputs[input_name]['uart_location']
            if dict_has_value('ftdi_location'):
                new_input.uart_location = dict_inputs[input_name]['ftdi_location']
            if dict_has_value('uart_baud_rate'):
                new_input.baud_rate = dict_inputs[input_name]['uart_baud_rate']
            if dict_has_value('pin_cs'):
                new_input.pin_cs = dict_inputs[input_name]['pin_cs']
            if dict_has_value('pin_miso'):
                new_input.pin_miso = dict_inputs[input_name]['pin_miso']
            if dict_has_value('pin_mosi'):
                new_input.pin_mosi = dict_inputs[input_name]['pin_mosi']
            if dict_has_value('pin_clock'):
                new_input.pin_clock = dict_inputs[input_name]['pin_clock']

            # Bluetooth (BT) options
            elif input_interface == 'BT':
                if dict_has_value('bt_location'):
                    new_input.location = dict_inputs[input_name]['bt_location']
                if dict_has_value('bt_adapter'):
                    new_input.bt_adapter = dict_inputs[input_name]['bt_adapter']

            # GPIO options
            elif input_interface == 'GPIO':
                if dict_has_value('gpio_location'):
                    new_input.gpio_location = dict_inputs[input_name]['gpio_location']

            # Custom location location
            elif dict_has_value('location'):
                new_input.location = dict_inputs[input_name]['location']['options'][0][0]  # First entry in list

            #
            # General options
            #

            if dict_has_value('period'):
                new_input.period = dict_inputs[input_name]['period']

            # Server Ping options
            if dict_has_value('times_check'):
                new_input.times_check = dict_inputs[input_name]['times_check']
            if dict_has_value('deadline'):
                new_input.deadline = dict_inputs[input_name]['deadline']
            if dict_has_value('port'):
                new_input.port = dict_inputs[input_name]['port']

            # Signal options
            if dict_has_value('weighting'):
                new_input.weighting = dict_inputs[input_name]['weighting']
            if dict_has_value('sample_time'):
                new_input.sample_time = dict_inputs[input_name]['sample_time']

            # Analog-to-digital converter options
            if dict_has_value('adc_gain'):
                if len(dict_inputs[input_name]['adc_gain']) == 1:
                    new_input.adc_gain = dict_inputs[input_name]['adc_gain'][0]
                elif len(dict_inputs[input_name]['adc_gain']) > 1:
                    new_input.adc_gain = dict_inputs[input_name]['adc_gain'][0][0]
            if dict_has_value('adc_resolution'):
                if len(dict_inputs[input_name]['adc_resolution']) == 1:
                    new_input.adc_resolution = dict_inputs[input_name]['adc_resolution'][0]
                elif len(dict_inputs[input_name]['adc_resolution']) > 1:
                    new_input.adc_resolution = dict_inputs[input_name]['adc_resolution'][0][0]
            if dict_has_value('adc_sample_speed'):
                if len(dict_inputs[input_name]['adc_sample_speed']) == 1:
                    new_input.adc_sample_speed = dict_inputs[input_name]['adc_sample_speed'][0]
                elif len(dict_inputs[input_name]['adc_sample_speed']) > 1:
                    new_input.adc_sample_speed = dict_inputs[input_name]['adc_sample_speed'][0][0]

            # Linux command
            if dict_has_value('cmd_command'):
                new_input.cmd_command = dict_inputs[input_name]['cmd_command']

            # Misc options
            if dict_has_value('resolution'):
                if len(dict_inputs[input_name]['resolution']) == 1:
                    new_input.resolution = dict_inputs[input_name]['resolution'][0]
                elif len(dict_inputs[input_name]['resolution']) > 1:
                    new_input.resolution = dict_inputs[input_name]['resolution'][0][0]
            if dict_has_value('resolution_2'):
                if len(dict_inputs[input_name]['resolution_2']) == 1:
                    new_input.resolution_2 = dict_inputs[input_name]['resolution_2'][0]
                elif len(dict_inputs[input_name]['resolution_2']) > 1:
                    new_input.resolution_2 = dict_inputs[input_name]['resolution_2'][0][0]
            if dict_has_value('sensitivity'):
                if len(dict_inputs[input_name]['sensitivity']) == 1:
                    new_input.sensitivity = dict_inputs[input_name]['sensitivity'][0]
                elif len(dict_inputs[input_name]['sensitivity']) > 1:
                    new_input.sensitivity = dict_inputs[input_name]['sensitivity'][0][0]
            if dict_has_value('thermocouple_type'):
                if len(dict_inputs[input_name]['thermocouple_type']) == 1:
                    new_input.thermocouple_type = dict_inputs[input_name]['thermocouple_type'][0]
                elif len(dict_inputs[input_name]['thermocouple_type']) > 1:
                    new_input.thermocouple_type = dict_inputs[input_name]['thermocouple_type'][0][0]
            if dict_has_value('sht_voltage'):
                if len(dict_inputs[input_name]['sht_voltage']) == 1:
                    new_input.sht_voltage = dict_inputs[input_name]['sht_voltage'][0]
                elif len(dict_inputs[input_name]['sht_voltage']) > 1:
                    new_input.sht_voltage = dict_inputs[input_name]['sht_voltage'][0][0]
            if dict_has_value('ref_ohm'):
                new_input.ref_ohm = dict_inputs[input_name]['ref_ohm']

        #
        # Custom Options
        #

        list_options = []
        if 'custom_options' in dict_inputs[input_name]:
            for each_option in dict_inputs[input_name]['custom_options']:
                if each_option['default_value'] is False:
                    default_value = ''
                else:
                    default_value = each_option['default_value']
                option = '{id},{value}'.format(
                    id=each_option['id'],
                    value=default_value)
                list_options.append(option)
        new_input.custom_options = ';'.join(list_options)

        try:
            if not error:
                new_input.save()

                display_order = csv_to_list_of_str(
                    DisplayOrder.query.first().inputs)

                DisplayOrder.query.first().inputs = add_display_order(
                    display_order, new_input.unique_id)
                db.session.commit()

                if ('measurements_dict' in dict_inputs[input_name] and
                        dict_inputs[input_name]['measurements_dict'] != []):
                    for each_channel in dict_inputs[input_name]['measurements_dict']:
                        measure_info = dict_inputs[input_name]['measurements_dict'][each_channel]
                        new_measurement = DeviceMeasurements()
                        if 'name' in measure_info:
                            new_measurement.name = measure_info['name']
                        new_measurement.device_id = new_input.unique_id
                        new_measurement.measurement = measure_info['measurement']
                        new_measurement.unit = measure_info['unit']
                        new_measurement.channel = each_channel
                        new_measurement.save()

                flash(gettext(
                    "%(type)s Input with ID %(id)s (%(uuid)s) successfully added",
                    type=input_name,
                    id=new_input.id,
                    uuid=new_input.unique_id),
                      "success")
        except sqlalchemy.exc.OperationalError as except_msg:
            error.append(except_msg)
        except sqlalchemy.exc.IntegrityError as except_msg:
            error.append(except_msg)

        flash_success_errors(error, action, url_for('routes_page.page_data'))
    else:
        flash_form_errors(form_add)

    if dep_unmet:
        return 1
Exemple #35
0
def input_add(form_add):
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['add']['title'],
        controller=TRANSLATIONS['input']['title'])
    error = []

    dict_inputs = parse_input_information()

    # only one comma should be in the input_type string
    if form_add.input_type.data.count(',') > 1:
        error.append("Invalid input module formatting. It appears there is "
                     "a comma in either 'input_name_unique' or 'interfaces'.")

    if form_add.input_type.data.count(',') == 1:
        input_name = form_add.input_type.data.split(',')[0]
        input_interface = form_add.input_type.data.split(',')[1]
    else:
        input_name = ''
        input_interface = ''
        error.append("Invalid input string (must be a comma-separated string)")

    if current_app.config['TESTING']:
        dep_unmet = False
    else:
        dep_unmet, _ = return_dependencies(input_name)
        if dep_unmet:
            list_unmet_deps = []
            for each_dep in dep_unmet:
                list_unmet_deps.append(each_dep[0])
            error.append(
                "The {dev} device you're trying to add has unmet dependencies: {dep}"
                .format(dev=input_name, dep=', '.join(list_unmet_deps)))

    if form_add.validate():
        new_input = Input()
        new_input.device = input_name

        if input_interface:
            new_input.interface = input_interface

        try:
            from RPi import GPIO
            if GPIO.RPI_INFO['P1_REVISION'] == 1:
                new_input.i2c_bus = 0
            else:
                new_input.i2c_bus = 1
        except:
            logger.error("RPi.GPIO and Raspberry Pi required for this action")

        if 'input_name' in dict_inputs[input_name]:
            new_input.name = dict_inputs[input_name]['input_name']
        else:
            new_input.name = 'Name'

        #
        # Set default values for new input being added
        #

        # input add options
        if input_name in dict_inputs:

            def dict_has_value(key):
                if (key in dict_inputs[input_name]
                        and (dict_inputs[input_name][key]
                             or dict_inputs[input_name][key] == 0)):
                    return True

            #
            # Interfacing options
            #

            if input_interface == 'I2C':
                if dict_has_value('i2c_location'):
                    new_input.i2c_location = dict_inputs[input_name][
                        'i2c_location'][0]  # First entry in list

            if input_interface == 'FTDI':
                if dict_has_value('ftdi_location'):
                    new_input.ftdi_location = dict_inputs[input_name][
                        'ftdi_location']

            if input_interface == 'UART':
                if dict_has_value('uart_location'):
                    new_input.uart_location = dict_inputs[input_name][
                        'uart_location']

            # UART options
            if dict_has_value('uart_baud_rate'):
                new_input.baud_rate = dict_inputs[input_name]['uart_baud_rate']
            if dict_has_value('pin_cs'):
                new_input.pin_cs = dict_inputs[input_name]['pin_cs']
            if dict_has_value('pin_miso'):
                new_input.pin_miso = dict_inputs[input_name]['pin_miso']
            if dict_has_value('pin_mosi'):
                new_input.pin_mosi = dict_inputs[input_name]['pin_mosi']
            if dict_has_value('pin_clock'):
                new_input.pin_clock = dict_inputs[input_name]['pin_clock']

            # Bluetooth (BT) options
            elif input_interface == 'BT':
                if dict_has_value('bt_location'):
                    new_input.location = dict_inputs[input_name]['bt_location']
                if dict_has_value('bt_adapter'):
                    new_input.bt_adapter = dict_inputs[input_name][
                        'bt_adapter']

            # GPIO options
            elif input_interface == 'GPIO':
                if dict_has_value('gpio_location'):
                    new_input.gpio_location = dict_inputs[input_name][
                        'gpio_location']

            # Custom location location
            elif dict_has_value('location'):
                new_input.location = dict_inputs[input_name]['location'][
                    'options'][0][0]  # First entry in list

            #
            # General options
            #

            if dict_has_value('period'):
                new_input.period = dict_inputs[input_name]['period']

            # Server Ping options
            if dict_has_value('times_check'):
                new_input.times_check = dict_inputs[input_name]['times_check']
            if dict_has_value('deadline'):
                new_input.deadline = dict_inputs[input_name]['deadline']
            if dict_has_value('port'):
                new_input.port = dict_inputs[input_name]['port']

            # Signal options
            if dict_has_value('weighting'):
                new_input.weighting = dict_inputs[input_name]['weighting']
            if dict_has_value('sample_time'):
                new_input.sample_time = dict_inputs[input_name]['sample_time']

            # Analog-to-digital converter options
            if dict_has_value('adc_gain'):
                if len(dict_inputs[input_name]['adc_gain']) == 1:
                    new_input.adc_gain = dict_inputs[input_name]['adc_gain'][0]
                elif len(dict_inputs[input_name]['adc_gain']) > 1:
                    new_input.adc_gain = dict_inputs[input_name]['adc_gain'][
                        0][0]
            if dict_has_value('adc_resolution'):
                if len(dict_inputs[input_name]['adc_resolution']) == 1:
                    new_input.adc_resolution = dict_inputs[input_name][
                        'adc_resolution'][0]
                elif len(dict_inputs[input_name]['adc_resolution']) > 1:
                    new_input.adc_resolution = dict_inputs[input_name][
                        'adc_resolution'][0][0]
            if dict_has_value('adc_sample_speed'):
                if len(dict_inputs[input_name]['adc_sample_speed']) == 1:
                    new_input.adc_sample_speed = dict_inputs[input_name][
                        'adc_sample_speed'][0]
                elif len(dict_inputs[input_name]['adc_sample_speed']) > 1:
                    new_input.adc_sample_speed = dict_inputs[input_name][
                        'adc_sample_speed'][0][0]

            # Linux command
            if dict_has_value('cmd_command'):
                new_input.cmd_command = dict_inputs[input_name]['cmd_command']

            # Misc options
            if dict_has_value('resolution'):
                if len(dict_inputs[input_name]['resolution']) == 1:
                    new_input.resolution = dict_inputs[input_name][
                        'resolution'][0]
                elif len(dict_inputs[input_name]['resolution']) > 1:
                    new_input.resolution = dict_inputs[input_name][
                        'resolution'][0][0]
            if dict_has_value('resolution_2'):
                if len(dict_inputs[input_name]['resolution_2']) == 1:
                    new_input.resolution_2 = dict_inputs[input_name][
                        'resolution_2'][0]
                elif len(dict_inputs[input_name]['resolution_2']) > 1:
                    new_input.resolution_2 = dict_inputs[input_name][
                        'resolution_2'][0][0]
            if dict_has_value('sensitivity'):
                if len(dict_inputs[input_name]['sensitivity']) == 1:
                    new_input.sensitivity = dict_inputs[input_name][
                        'sensitivity'][0]
                elif len(dict_inputs[input_name]['sensitivity']) > 1:
                    new_input.sensitivity = dict_inputs[input_name][
                        'sensitivity'][0][0]
            if dict_has_value('thermocouple_type'):
                if len(dict_inputs[input_name]['thermocouple_type']) == 1:
                    new_input.thermocouple_type = dict_inputs[input_name][
                        'thermocouple_type'][0]
                elif len(dict_inputs[input_name]['thermocouple_type']) > 1:
                    new_input.thermocouple_type = dict_inputs[input_name][
                        'thermocouple_type'][0][0]
            if dict_has_value('sht_voltage'):
                if len(dict_inputs[input_name]['sht_voltage']) == 1:
                    new_input.sht_voltage = dict_inputs[input_name][
                        'sht_voltage'][0]
                elif len(dict_inputs[input_name]['sht_voltage']) > 1:
                    new_input.sht_voltage = dict_inputs[input_name][
                        'sht_voltage'][0][0]
            if dict_has_value('ref_ohm'):
                new_input.ref_ohm = dict_inputs[input_name]['ref_ohm']

        #
        # Custom Options
        #

        # Generate string to save from custom options
        error, custom_options = custom_options_return_json(error,
                                                           dict_inputs,
                                                           device=input_name,
                                                           use_defaults=True)
        new_input.custom_options = custom_options

        #
        # Execute at Creation
        #

        new_input.unique_id = set_uuid()

        if ('execute_at_creation' in dict_inputs[new_input.device]
                and not current_app.config['TESTING']):
            new_input = dict_inputs[new_input.device]['execute_at_creation'](
                new_input, dict_inputs[new_input.device])

        try:
            if not error:
                new_input.save()

                display_order = csv_to_list_of_str(
                    DisplayOrder.query.first().inputs)

                DisplayOrder.query.first().inputs = add_display_order(
                    display_order, new_input.unique_id)
                db.session.commit()

                #
                # If there are a variable number of measurements
                #

                if ('measurements_variable_amount' in dict_inputs[input_name]
                        and dict_inputs[input_name]
                    ['measurements_variable_amount']):
                    # Add first default measurement with empty unit and measurement
                    new_measurement = DeviceMeasurements()
                    new_measurement.name = ""
                    new_measurement.device_id = new_input.unique_id
                    new_measurement.measurement = ""
                    new_measurement.unit = ""
                    new_measurement.channel = 0
                    new_measurement.save()

                #
                # If measurements defined in the Input Module
                #

                elif ('measurements_dict' in dict_inputs[input_name]
                      and dict_inputs[input_name]['measurements_dict'] != []):
                    for each_channel in dict_inputs[input_name][
                            'measurements_dict']:
                        measure_info = dict_inputs[input_name][
                            'measurements_dict'][each_channel]
                        new_measurement = DeviceMeasurements()
                        if 'name' in measure_info:
                            new_measurement.name = measure_info['name']
                        new_measurement.device_id = new_input.unique_id
                        new_measurement.measurement = measure_info[
                            'measurement']
                        new_measurement.unit = measure_info['unit']
                        new_measurement.channel = each_channel
                        new_measurement.save()

                flash(
                    gettext(
                        "%(type)s Input with ID %(id)s (%(uuid)s) successfully added",
                        type=input_name,
                        id=new_input.id,
                        uuid=new_input.unique_id), "success")
        except sqlalchemy.exc.OperationalError as except_msg:
            error.append(except_msg)
        except sqlalchemy.exc.IntegrityError as except_msg:
            error.append(except_msg)

        flash_success_errors(error, action, url_for('routes_page.page_data'))
    else:
        flash_form_errors(form_add)

    if dep_unmet:
        return 1
Exemple #36
0
def page_output():
    """Display Output page options."""
    output_type = request.args.get('output_type', None)
    output_id = request.args.get('output_id', None)
    each_output = None
    if output_type in ['entry', 'options'] and output_id != '0':
        each_output = Output.query.filter(
            Output.unique_id == output_id).first()

    camera = Camera.query.all()
    function = CustomController.query.all()
    input_dev = Input.query.all()
    method = Method.query.all()
    misc = Misc.query.first()
    output = Output.query.all()
    output_channel = OutputChannel
    pid = PID.query.all()
    user = User.query.all()

    dict_outputs = parse_output_information()

    form_add_output = forms_output.OutputAdd()
    form_mod_output = forms_output.OutputMod()

    # Generate all measurement and units used
    dict_measurements = add_custom_measurements(Measurement.query.all())
    dict_units = add_custom_units(Unit.query.all())

    choices_function = utils_general.choices_functions(function, dict_units,
                                                       dict_measurements)
    choices_input = utils_general.choices_inputs(input_dev, dict_units,
                                                 dict_measurements)
    choices_input_devices = utils_general.choices_input_devices(input_dev)
    choices_method = utils_general.choices_methods(method)
    choices_output = utils_general.choices_outputs(output, OutputChannel,
                                                   dict_outputs, dict_units,
                                                   dict_measurements)
    choices_output_channels = utils_general.choices_outputs_channels(
        output, output_channel.query.all(), dict_outputs)
    choices_pid = utils_general.choices_pids(pid, dict_units,
                                             dict_measurements)

    custom_options_values_outputs = parse_custom_option_values_json(
        output, dict_controller=dict_outputs)
    custom_options_values_output_channels = parse_custom_option_values_output_channels_json(
        output_channel.query.all(),
        dict_controller=dict_outputs,
        key_name='custom_channel_options')

    custom_commands = {}
    for each_output_dev in output:
        if 'custom_commands' in dict_outputs[each_output_dev.output_type]:
            custom_commands[each_output_dev.output_type] = True

    # Create dict of Input names
    names_output = {}
    all_elements = output
    for each_element in all_elements:
        names_output[each_element.unique_id] = '[{id}] {name}'.format(
            id=each_element.unique_id.split('-')[0], name=each_element.name)

    # Create list of file names from the output_options directory
    # Used in generating the correct options for each output/device
    output_templates = []
    output_path = os.path.join(
        INSTALL_DIRECTORY,
        'mycodo/mycodo_flask/templates/pages/output_options')
    for (_, _, file_names) in os.walk(output_path):
        output_templates.extend(file_names)
        break

    display_order_output = csv_to_list_of_str(
        DisplayOrder.query.first().output)

    output_variables = {}
    for each_output_dev in output:
        output_variables[each_output_dev.unique_id] = {}
        for each_channel in dict_outputs[
                each_output_dev.output_type]['channels_dict']:
            output_variables[each_output_dev.unique_id][each_channel] = {}
            output_variables[
                each_output_dev.unique_id][each_channel]['amps'] = None
            output_variables[each_output_dev.
                             unique_id][each_channel]['trigger_startup'] = None

    # Find FTDI devices
    ftdi_devices = []
    if not current_app.config['TESTING']:
        for each_output_dev in output:
            if each_output_dev.interface == "FTDI":
                from mycodo.devices.atlas_scientific_ftdi import get_ftdi_device_list
                ftdi_devices = get_ftdi_device_list()
                break

    if not output_type:
        return render_template(
            'pages/output.html',
            camera=camera,
            choices_function=choices_function,
            choices_input=choices_input,
            choices_input_devices=choices_input_devices,
            choices_method=choices_method,
            choices_output=choices_output,
            choices_output_channels=choices_output_channels,
            choices_pid=choices_pid,
            custom_commands=custom_commands,
            custom_options_values_outputs=custom_options_values_outputs,
            custom_options_values_output_channels=
            custom_options_values_output_channels,
            dict_outputs=dict_outputs,
            display_order_output=display_order_output,
            form_add_output=form_add_output,
            form_mod_output=form_mod_output,
            ftdi_devices=ftdi_devices,
            misc=misc,
            names_output=names_output,
            output=output,
            output_channel=output_channel,
            output_types=output_types(),
            output_templates=output_templates,
            output_variables=output_variables,
            user=user)
    elif output_type == 'entry':
        return render_template(
            'pages/output_entry.html',
            camera=camera,
            choices_function=choices_function,
            choices_input=choices_input,
            choices_input_devices=choices_input_devices,
            choices_method=choices_method,
            choices_output=choices_output,
            choices_output_channels=choices_output_channels,
            choices_pid=choices_pid,
            custom_commands=custom_commands,
            custom_options_values_outputs=custom_options_values_outputs,
            custom_options_values_output_channels=
            custom_options_values_output_channels,
            dict_outputs=dict_outputs,
            display_order_output=display_order_output,
            each_output=each_output,
            form_add_output=form_add_output,
            form_mod_output=form_mod_output,
            ftdi_devices=ftdi_devices,
            misc=misc,
            names_output=names_output,
            output=output,
            output_channel=output_channel,
            output_types=output_types(),
            output_templates=output_templates,
            output_variables=output_variables,
            user=user)
    elif output_type == 'options':
        return render_template(
            'pages/output_options.html',
            camera=camera,
            choices_function=choices_function,
            choices_input=choices_input,
            choices_input_devices=choices_input_devices,
            choices_method=choices_method,
            choices_output=choices_output,
            choices_output_channels=choices_output_channels,
            choices_pid=choices_pid,
            custom_commands=custom_commands,
            custom_options_values_outputs=custom_options_values_outputs,
            custom_options_values_output_channels=
            custom_options_values_output_channels,
            dict_outputs=dict_outputs,
            display_order_output=display_order_output,
            each_output=each_output,
            form_add_output=form_add_output,
            form_mod_output=form_mod_output,
            ftdi_devices=ftdi_devices,
            misc=misc,
            names_output=names_output,
            output=output,
            output_channel=output_channel,
            output_types=output_types(),
            output_templates=output_templates,
            output_variables=output_variables,
            user=user)
Exemple #37
0
def method_mod(form_mod_method):
    action = '{action} {controller}'.format(action=gettext("Modify"),
                                            controller=gettext("Method"))
    error = []

    method = Method.query.filter(
        Method.unique_id == form_mod_method.method_id.data).first()
    method_data = MethodData.query.filter(
        MethodData.unique_id == form_mod_method.method_data_id.data).first()
    display_order = csv_to_list_of_str(method.method_order)

    try:
        if form_mod_method.Delete.data:
            delete_entry_with_id(MethodData,
                                 form_mod_method.method_data_id.data)
            if form_mod_method.method_select.data != 'output':
                method_order = Method.query.filter(
                    Method.unique_id == method.unique_id).first()
                display_order = csv_to_list_of_str(method_order.method_order)
                display_order.remove(method_data.unique_id)
                method_order.method_order = list_to_csv(display_order)
                db.session.commit()
            return 0

        if form_mod_method.rename.data:
            method.name = form_mod_method.name.data
            db.session.commit()
            return 0

        # Ensure data is valid
        if validate_method_data(form_mod_method, method):
            return 1

        if form_mod_method.method_select.data == 'setpoint':
            if method.method_type == 'Date':
                start_time = datetime.strptime(form_mod_method.time_start.data,
                                               '%Y-%m-%d %H:%M:%S')
                end_time = datetime.strptime(form_mod_method.time_end.data,
                                             '%Y-%m-%d %H:%M:%S')

                # Ensure the start time comes after the previous entry's end time
                # and the end time comes before the next entry's start time
                # method_id_set is the id given to all method entries, 'method_id', not 'id'
                previous_method = None
                next_method = None
                for index, each_order in enumerate(display_order):
                    if each_order == method_data.unique_id:
                        if len(display_order) > 1 and index > 0:
                            previous_method = MethodData.query.filter(
                                MethodData.unique_id == display_order[
                                    index - 1]).first()
                        if len(display_order) > index + 1:
                            next_method = MethodData.query.filter(
                                MethodData.unique_id == display_order[
                                    index + 1]).first()

                if previous_method is not None and previous_method.time_end is not None:
                    previous_end_time = datetime.strptime(
                        previous_method.time_end, '%Y-%m-%d %H:%M:%S')
                    if previous_end_time is not None and start_time < previous_end_time:
                        error.append(
                            gettext(
                                "The entry start time (%(st)s) cannot "
                                "overlap the previous entry's end time "
                                "(%(et)s)",
                                st=start_time,
                                et=previous_end_time))

                if next_method is not None and next_method.time_start is not None:
                    next_start_time = datetime.strptime(
                        next_method.time_start, '%Y-%m-%d %H:%M:%S')
                    if next_start_time is not None and end_time > next_start_time:
                        error.append(
                            gettext(
                                "The entry end time (%(et)s) cannot "
                                "overlap the next entry's start time "
                                "(%(st)s)",
                                et=end_time,
                                st=next_start_time))

                method_data.time_start = start_time.strftime(
                    '%Y-%m-%d %H:%M:%S')
                method_data.time_end = end_time.strftime('%Y-%m-%d %H:%M:%S')

            elif method.method_type == 'Duration':
                if method_data.duration_sec == 0:
                    method_data.duration_end = form_mod_method.duration_end.data
                else:
                    method_data.duration_sec = form_mod_method.duration.data

            elif method.method_type == 'Daily':
                method_data.time_start = form_mod_method.daily_time_start.data
                method_data.time_end = form_mod_method.daily_time_end.data

            method_data.setpoint_start = form_mod_method.setpoint_start.data
            method_data.setpoint_end = form_mod_method.setpoint_end.data

        elif form_mod_method.method_select.data == 'output':
            if method.method_type == 'Date':
                method_data.time_start = form_mod_method.output_time.data
            elif method.method_type == 'Duration':
                method_data.duration_sec = form_mod_method.duration.data
                if form_mod_method.duration_sec.data == 0:
                    method_data.duration_end = form_mod_method.duration_end.data
            if form_mod_method.output_id.data == '':
                method_data.output_id = None
            else:
                method_data.output_id = form_mod_method.output_id.data
            method_data.output_state = form_mod_method.output_state.data
            method_data.output_duration = form_mod_method.output_duration.data

        elif method.method_type == 'DailySine':
            if form_mod_method.method_select.data == 'output':
                method_data.time_start = form_mod_method.output_time.data
                if form_mod_method.output_id.data == '':
                    method_data.output_id = None
                else:
                    method_data.output_id = form_mod_method.output_id.data
                method_data.output_state = form_mod_method.output_state.data
                method_data.output_duration = form_mod_method.output_duration.data

        if not error:
            db.session.commit()

    except Exception as except_msg:
        error.append(except_msg)
    flash_success_errors(error, action, url_for('routes_method.method_list'))
Exemple #38
0
def method_add(form_add_method):
    """ Add line to method_data table """
    action = '{action} {controller}'.format(action=gettext("Add"),
                                            controller=gettext("Method"))
    error = []

    method = Method.query.filter(
        Method.unique_id == form_add_method.method_id.data).first()
    display_order = csv_to_list_of_str(method.method_order)

    try:
        if validate_method_data(form_add_method, method):
            return 1

        if method.method_type == 'DailySine':
            add_method_data = MethodData.query.filter(
                MethodData.method_id ==
                form_add_method.method_id.data).first()
            add_method_data.amplitude = form_add_method.amplitude.data
            add_method_data.frequency = form_add_method.frequency.data
            add_method_data.shift_angle = form_add_method.shift_angle.data
            add_method_data.shift_y = form_add_method.shiftY.data
            db.session.commit()
            return 0

        elif method.method_type == 'DailyBezier':
            if not 0 <= form_add_method.shift_angle.data <= 360:
                flash(
                    gettext("Error: Angle Shift is out of range. It must be "
                            "<= 0 and <= 360."), "error")
                return 1
            if form_add_method.x0.data <= form_add_method.x3.data:
                flash(gettext("Error: X0 must be greater than X3."), "error")
                return 1
            add_method_data = MethodData.query.filter(
                MethodData.method_id ==
                form_add_method.method_id.data).first()
            add_method_data.shift_angle = form_add_method.shift_angle.data
            add_method_data.x0 = form_add_method.x0.data
            add_method_data.y0 = form_add_method.y0.data
            add_method_data.x1 = form_add_method.x1.data
            add_method_data.y1 = form_add_method.y1.data
            add_method_data.x2 = form_add_method.x2.data
            add_method_data.y2 = form_add_method.y2.data
            add_method_data.x3 = form_add_method.x3.data
            add_method_data.y3 = form_add_method.y3.data
            db.session.commit()
            return 0

        if form_add_method.method_select.data == 'setpoint':
            if method.method_type == 'Date':
                start_time = datetime.strptime(form_add_method.time_start.data,
                                               '%Y-%m-%d %H:%M:%S')
                end_time = datetime.strptime(form_add_method.time_end.data,
                                             '%Y-%m-%d %H:%M:%S')
            elif method.method_type == 'Daily':
                start_time = datetime.strptime(
                    form_add_method.daily_time_start.data, '%H:%M:%S')
                end_time = datetime.strptime(
                    form_add_method.daily_time_end.data, '%H:%M:%S')

            if method.method_type in ['Date', 'Daily']:
                # Check if the start time comes after the last entry's end time
                display_order = csv_to_list_of_str(method.method_order)
                if display_order:
                    last_method = MethodData.query.filter(
                        MethodData.unique_id == display_order[-1]).first()
                else:
                    last_method = None

                if last_method is not None:
                    if method.method_type == 'Date':
                        last_method_end_time = datetime.strptime(
                            last_method.time_end, '%Y-%m-%d %H:%M:%S')
                    elif method.method_type == 'Daily':
                        last_method_end_time = datetime.strptime(
                            last_method.time_end, '%H:%M:%S')

                    if start_time < last_method_end_time:
                        flash(
                            gettext(
                                "The new entry start time (%(st)s) "
                                "cannot overlap the last entry's end "
                                "time (%(et)s). Note: They may be the "
                                "same time.",
                                st=last_method_end_time,
                                et=start_time), "error")
                        return 1

        elif form_add_method.method_select.data == 'output':
            if method.method_type == 'Date':
                start_time = datetime.strptime(
                    form_add_method.output_time.data, '%Y-%m-%d %H:%M:%S')
            elif method.method_type == 'Daily':
                start_time = datetime.strptime(
                    form_add_method.output_daily_time.data, '%H:%M:%S')

        add_method_data = MethodData()
        add_method_data.method_id = form_add_method.method_id.data

        if method.method_type == 'Date':
            if form_add_method.method_select.data == 'setpoint':
                add_method_data.time_start = start_time.strftime(
                    '%Y-%m-%d %H:%M:%S')
                add_method_data.time_end = end_time.strftime(
                    '%Y-%m-%d %H:%M:%S')
            if form_add_method.method_select.data == 'output':
                add_method_data.time_start = form_add_method.output_time.data
        elif method.method_type == 'Daily':
            if form_add_method.method_select.data == 'setpoint':
                add_method_data.time_start = start_time.strftime('%H:%M:%S')
                add_method_data.time_end = end_time.strftime('%H:%M:%S')
            if form_add_method.method_select.data == 'output':
                add_method_data.time_start = form_add_method.output_daily_time.data
        elif method.method_type == 'Duration':
            if form_add_method.restart.data:
                add_method_data.duration_sec = 0
                add_method_data.duration_end = form_add_method.duration_end.data
            else:
                add_method_data.duration_sec = form_add_method.duration.data

        if form_add_method.method_select.data == 'setpoint':
            add_method_data.setpoint_start = form_add_method.setpoint_start.data
            add_method_data.setpoint_end = form_add_method.setpoint_end.data
        elif form_add_method.method_select.data == 'output':
            add_method_data.output_id = form_add_method.output_id.data
            add_method_data.output_state = form_add_method.output_state.data
            add_method_data.output_duration = form_add_method.output_duration.data

        db.session.add(add_method_data)
        db.session.commit()

        # Add line to method data list if not a output duration
        if form_add_method.method_select.data != 'output':
            method.method_order = add_display_order(display_order,
                                                    add_method_data.unique_id)
            db.session.commit()

        if form_add_method.method_select.data == 'setpoint':
            if method.method_type == 'Date':
                flash(
                    gettext(
                        "Added duration to method from %(st)s to "
                        "%(end)s",
                        st=start_time,
                        end=end_time), "success")
            elif method.method_type == 'Daily':
                flash(
                    gettext(
                        "Added duration to method from %(st)s to "
                        "%(end)s",
                        st=start_time.strftime('%H:%M:%S'),
                        end=end_time.strftime('%H:%M:%S')), "success")
            elif method.method_type == 'Duration':
                if form_add_method.restart.data:
                    flash(gettext("Added method restart"), "success")
                else:
                    flash(
                        gettext("Added duration to method for %(sec)s seconds",
                                sec=form_add_method.duration.data), "success")
        elif form_add_method.method_select.data == 'output':
            if method.method_type == 'Date':
                flash(
                    gettext(
                        "Added output modulation to method at start "
                        "time: %(tm)s",
                        tm=start_time), "success")
            elif method.method_type == 'Daily':
                flash(
                    gettext(
                        "Added output modulation to method at start "
                        "time: %(tm)s",
                        tm=start_time.strftime('%H:%M:%S')), "success")
            elif method.method_type == 'Duration':
                flash(
                    gettext(
                        "Added output modulation to method at start "
                        "time: %(tm)s",
                        tm=form_add_method.duration.data), "success")

    except Exception as except_msg:
        logger.exception(1)
        error.append(except_msg)
    flash_success_errors(error, action, url_for('routes_method.method_list'))
Exemple #39
0
def method_create(form_create_method):
    """ Create new method table entry (all data stored in method_data table) """
    action = '{action} {controller}'.format(action=gettext("Create"),
                                            controller=gettext("Method"))
    error = []

    try:
        # Create method
        new_method = Method()
        new_method.name = form_create_method.name.data
        new_method.method_type = form_create_method.method_type.data
        db.session.add(new_method)
        db.session.commit()

        # Add new method line id to method display order
        method_order = DisplayOrder.query.first()
        display_order = csv_to_list_of_str(method_order.method)
        method_order.method = add_display_order(display_order,
                                                new_method.unique_id)
        db.session.commit()

        # Add new method data line id to method_data display order
        if new_method.method_type in ['DailyBezier', 'DailySine']:
            # For tables that require only one entry to configure,
            # create that single entry now with default values
            new_method_data = MethodData()
            new_method_data.method_id = new_method.unique_id

            if new_method.method_type == 'DailySine':
                new_method_data.amplitude = 1.0
                new_method_data.frequency = 1.0
                new_method_data.shift_angle = 0
                new_method_data.shift_y = 1.0
            elif new_method.method_type == 'DailyBezier':
                new_method_data = MethodData()
                new_method_data.method_id = new_method.unique_id
                new_method_data.shift_angle = 0.0
                new_method_data.x0 = 20.0
                new_method_data.y0 = 20.0
                new_method_data.x1 = 10.0
                new_method_data.y1 = 13.5
                new_method_data.x2 = 22.5
                new_method_data.y2 = 30.0
                new_method_data.x3 = 0.0
                new_method_data.y3 = 20.0

            db.session.add(new_method_data)
            db.session.commit()

            display_order = csv_to_list_of_str(new_method.method_order)
            method = Method.query.filter(
                Method.unique_id == new_method.unique_id).first()
            method.method_order = add_display_order(display_order,
                                                    new_method_data.unique_id)
            db.session.commit()

        return 0
    except Exception as except_msg:

        error.append(except_msg)
    flash_success_errors(error, action, url_for('routes_method.method_list'))
Exemple #40
0
def function_add(form_add_func):
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['add']['title'],
        controller=TRANSLATIONS['function']['title'])
    error = []

    new_func = None

    try:
        if form_add_func.func_type.data.startswith('conditional_'):
            new_func = Conditional()
            new_func.conditional_statement = '''
# Replace "asdf1234" with a Condition ID, "qwer5678" with an Action ID.
measurement = measure("{asdf1234}")
message += "Measure: {meas}".format(meas=measurement)
if measurement is not None:  # If a measurement exists
    if measurement < 23:  # If the measurement is less than 23
        run_all_actions(message=message)  # Run all actions
    else:  # If the measurement is greater or equal to 23
        run_action("{qwer5678}", message=message)  # Run a single Action'''
            new_func.save()
        elif form_add_func.func_type.data.startswith('pid_'):
            new_func = PID().save()

            for each_channel, measure_info in PID_INFO['measure'].items():
                new_measurement = DeviceMeasurements()

                if 'name' in measure_info:
                    new_measurement.name = measure_info['name']
                if 'measurement_type' in measure_info:
                    new_measurement.measurement_type = measure_info['measurement_type']

                new_measurement.device_id = new_func.unique_id
                new_measurement.measurement = measure_info['measurement']
                new_measurement.unit = measure_info['unit']
                new_measurement.channel = each_channel
                new_measurement.save()

        elif form_add_func.func_type.data.startswith('trigger_'):
            new_func = Trigger()
            for name_id, name, _ in FUNCTION_TYPES:
                if form_add_func.func_type.data == name_id:
                    new_func.name = '{}'.format(name)
            new_func.trigger_type = form_add_func.func_type.data
            new_func.save()
        elif form_add_func.func_type.data.startswith('function_'):
            new_func = Function()
            if form_add_func.func_type.data == 'function_spacer':
                new_func.name = 'Spacer'
            new_func.function_type = form_add_func.func_type.data
            new_func.save()
        elif form_add_func.func_type.data == '':
            error.append("Must select a function type")
        else:
            error.append("Unknown function type: '{}'".format(
                form_add_func.func_type.data))

        if not error:
            display_order = csv_to_list_of_str(
                DisplayOrder.query.first().function)
            DisplayOrder.query.first().function = add_display_order(
                display_order, new_func.unique_id)
            db.session.commit()

    except sqlalchemy.exc.OperationalError as except_msg:
        error.append(except_msg)
    except sqlalchemy.exc.IntegrityError as except_msg:
        error.append(except_msg)
    except Exception as except_msg:
        error.append(except_msg)

    flash_success_errors(error, action, url_for('routes_page.page_function'))
Exemple #41
0
def output_add(form_add):
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['add']['title'],
        controller=TRANSLATIONS['output']['title'])
    error = []

    dep_unmet, _ = return_dependencies(form_add.output_type.data.split(',')[0])
    if dep_unmet:
        list_unmet_deps = []
        for each_dep in dep_unmet:
            list_unmet_deps.append(each_dep[0])
        error.append(
            "The {dev} device you're trying to add has unmet dependencies: "
            "{dep}".format(dev=form_add.output_type.data,
                           dep=', '.join(list_unmet_deps)))

    if len(form_add.output_type.data.split(',')) < 2:
        error.append("Must select an Output type")

    if not is_int(form_add.output_quantity.data, check_range=[1, 20]):
        error.append("{error}. {accepted_values}: 1-20".format(
            error=gettext("Invalid quantity"),
            accepted_values=gettext("Acceptable values")
        ))

    if not error:
        for _ in range(0, form_add.output_quantity.data):
            try:
                output_type = form_add.output_type.data.split(',')[0]
                interface = form_add.output_type.data.split(',')[1]

                new_output = Output()
                new_output.name = str(OUTPUT_INFO[output_type]['name'])
                new_output.output_type = output_type
                new_output.interface = interface

                if output_type in ['wired',
                                   'wireless_rpi_rf',
                                   'command',
                                   'python']:
                    new_output.measurement = 'duration_time'
                    new_output.unit = 's'
                elif output_type in ['command_pwm',
                                     'pwm',
                                     'python_pwm']:
                    new_output.measurement = 'duty_cycle'
                    new_output.unit = 'percent'
                elif output_type == 'atlas_ezo_pmp':
                    new_output.measurement = 'volume'
                    new_output.unit = 'ml'

                new_output.channel = 0

                if output_type == 'wired':
                    new_output.on_at_start = False
                elif output_type == 'wireless_rpi_rf':
                    new_output.pin = None
                    new_output.protocol = 1
                    new_output.pulse_length = 189
                    new_output.on_command = '22559'
                    new_output.off_command = '22558'
                elif output_type == 'command':
                    new_output.on_command = '/home/pi/script_on.sh'
                    new_output.off_command = '/home/pi/script_off.sh'
                elif output_type == 'command_pwm':
                    new_output.pwm_command = '/home/pi/script_pwm.sh ((duty_cycle))'
                elif output_type == 'pwm':
                    new_output.pwm_hertz = 22000
                    new_output.pwm_library = 'pigpio_any'
                elif output_type == 'python':
                    new_output.on_command = """
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
write_string = "{ts}: ID: {id}: ON\\n".format(id=output_id, ts=timestamp)
with open("/home/pi/Mycodo/OutputTest.txt", "a") as myfile:
    myfile.write(write_string)"""
                    new_output.off_command = """
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
write_string = "{ts}: ID: {id}: OFF\\n".format(id=output_id, ts=timestamp)
with open("/home/pi/Mycodo/OutputTest.txt", "a") as myfile:
    myfile.write(write_string)"""
                elif output_type == 'python_pwm':
                    new_output.pwm_command = """
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
write_string = "{ts}: ID: {id}: Duty Cycle: ((duty_cycle)) %\\n".format(
    id=output_id, ts=timestamp)
with open("/home/pi/Mycodo/OutputTest.txt", "a") as myfile:
    myfile.write(write_string)"""
                elif output_type == 'atlas_ezo_pmp':
                    new_output.flow_rate = 10
                    if interface == 'I2C':
                        new_output.location = '0x67'
                        new_output.i2c_bus = 1
                    elif interface == 'UART':
                        new_output.location = '/dev/ttyAMA0'
                        new_output.baud_rate = 9600

                if not error:
                    new_output.save()
                    display_order = csv_to_list_of_str(
                        DisplayOrder.query.first().output)
                    DisplayOrder.query.first().output = add_display_order(
                        display_order, new_output.unique_id)
                    db.session.commit()
                    manipulate_output('Add', new_output.unique_id)
            except sqlalchemy.exc.OperationalError as except_msg:
                error.append(except_msg)
            except sqlalchemy.exc.IntegrityError as except_msg:
                error.append(except_msg)

    flash_success_errors(error, action, url_for('routes_page.page_output'))

    if dep_unmet:
        return 1
Exemple #42
0
def method_create(form_create_method):
    """ Create new method table entry (all data stored in method_data table) """
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['add']['title'],
        controller=TRANSLATIONS['method']['title'])
    error = []

    try:
        # Create method
        new_method = Method()
        new_method.name = form_create_method.name.data
        new_method.method_type = form_create_method.method_type.data
        db.session.add(new_method)
        db.session.commit()

        # Add new method line id to method display order
        method_order = DisplayOrder.query.first()
        display_order = csv_to_list_of_str(method_order.method)
        method_order.method = add_display_order(display_order, new_method.unique_id)
        db.session.commit()

        # Add new method data line id to method_data display order
        if new_method.method_type in ['DailyBezier', 'DailySine']:
            # For tables that require only one entry to configure,
            # create that single entry now with default values
            new_method_data = MethodData()
            new_method_data.method_id = new_method.unique_id

            if new_method.method_type == 'DailySine':
                new_method_data.amplitude = 1.0
                new_method_data.frequency = 1.0
                new_method_data.shift_angle = 0
                new_method_data.shift_y = 1.0
            elif new_method.method_type == 'DailyBezier':
                new_method_data = MethodData()
                new_method_data.method_id = new_method.unique_id
                new_method_data.shift_angle = 0.0
                new_method_data.x0 = 20.0
                new_method_data.y0 = 20.0
                new_method_data.x1 = 10.0
                new_method_data.y1 = 13.5
                new_method_data.x2 = 22.5
                new_method_data.y2 = 30.0
                new_method_data.x3 = 0.0
                new_method_data.y3 = 20.0

            db.session.add(new_method_data)
            db.session.commit()

            display_order = csv_to_list_of_str(new_method.method_order)
            method = Method.query.filter(
                Method.unique_id == new_method.unique_id).first()
            method.method_order = add_display_order(
                display_order, new_method_data.unique_id)
            db.session.commit()

        return 0
    except Exception as except_msg:

        error.append(except_msg)
    flash_success_errors(error, action, url_for('routes_method.method_list'))
Exemple #43
0
def method_add(form_add_method):
    """ Add line to method_data table """
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['add']['title'],
        controller=TRANSLATIONS['method']['title'])
    error = []

    start_time = None
    end_time = None

    method = Method.query.filter(
        Method.unique_id == form_add_method.method_id.data).first()
    display_order = csv_to_list_of_str(method.method_order)

    try:
        if validate_method_data(form_add_method, method):
            return 1

        if method.method_type == 'DailySine':
            add_method_data = MethodData.query.filter(
                MethodData.method_id == form_add_method.method_id.data).first()
            add_method_data.amplitude = form_add_method.amplitude.data
            add_method_data.frequency = form_add_method.frequency.data
            add_method_data.shift_angle = form_add_method.shift_angle.data
            add_method_data.shift_y = form_add_method.shiftY.data
            db.session.commit()
            return 0

        elif method.method_type == 'DailyBezier':
            if not 0 <= form_add_method.shift_angle.data <= 360:
                flash(gettext("Error: Angle Shift is out of range. It must be "
                              "<= 0 and <= 360."), "error")
                return 1
            if form_add_method.x0.data <= form_add_method.x3.data:
                flash(gettext("Error: X0 must be greater than X3."), "error")
                return 1
            add_method_data = MethodData.query.filter(
                MethodData.method_id == form_add_method.method_id.data).first()
            add_method_data.shift_angle = form_add_method.shift_angle.data
            add_method_data.x0 = form_add_method.x0.data
            add_method_data.y0 = form_add_method.y0.data
            add_method_data.x1 = form_add_method.x1.data
            add_method_data.y1 = form_add_method.y1.data
            add_method_data.x2 = form_add_method.x2.data
            add_method_data.y2 = form_add_method.y2.data
            add_method_data.x3 = form_add_method.x3.data
            add_method_data.y3 = form_add_method.y3.data
            db.session.commit()
            return 0

        if form_add_method.method_select.data == 'setpoint':
            if method.method_type == 'Date':
                start_time = datetime.strptime(
                    form_add_method.time_start.data,
                    '%Y-%m-%d %H:%M:%S')
                end_time = datetime.strptime(
                    form_add_method.time_end.data,
                    '%Y-%m-%d %H:%M:%S')
            elif method.method_type == 'Daily':
                start_time = datetime.strptime(
                    form_add_method.daily_time_start.data,
                    '%H:%M:%S')
                end_time = datetime.strptime(
                    form_add_method.daily_time_end.data,
                    '%H:%M:%S')

            if method.method_type in ['Date', 'Daily']:
                # Check if the start time comes after the last entry's end time
                display_order = csv_to_list_of_str(method.method_order)
                if display_order:
                    last_method = MethodData.query.filter(
                        MethodData.unique_id == display_order[-1]).first()
                else:
                    last_method = None

                if last_method is not None:
                    if method.method_type == 'Date':
                        last_method_end_time = datetime.strptime(
                            last_method.time_end,
                            '%Y-%m-%d %H:%M:%S')
                    elif method.method_type == 'Daily':
                        last_method_end_time = datetime.strptime(
                            last_method.time_end,
                            '%H:%M:%S')
                    else:
                        last_method_end_time = None

                    if (start_time and last_method_end_time and
                            start_time < last_method_end_time):
                        flash(gettext("The new entry start time (%(st)s) "
                                      "cannot overlap the last entry's end "
                                      "time (%(et)s). Note: They may be the "
                                      "same time.",
                                      st=last_method_end_time,
                                      et=start_time),
                              "error")
                        return 1

        elif form_add_method.method_select.data == 'output':
            if method.method_type == 'Date':
                start_time = datetime.strptime(
                    form_add_method.output_time.data,
                    '%Y-%m-%d %H:%M:%S')
            elif method.method_type == 'Daily':
                start_time = datetime.strptime(
                    form_add_method.output_daily_time.data,
                    '%H:%M:%S')

        add_method_data = MethodData()
        add_method_data.method_id = form_add_method.method_id.data

        if method.method_type == 'Date':
            if form_add_method.method_select.data == 'setpoint':
                add_method_data.time_start = start_time.strftime(
                    '%Y-%m-%d %H:%M:%S')
                add_method_data.time_end = end_time.strftime(
                    '%Y-%m-%d %H:%M:%S')
            if form_add_method.method_select.data == 'output':
                add_method_data.time_start = form_add_method.output_time.data
        elif method.method_type == 'Daily':
            if form_add_method.method_select.data == 'setpoint':
                add_method_data.time_start = start_time.strftime('%H:%M:%S')
                add_method_data.time_end = end_time.strftime('%H:%M:%S')
            if form_add_method.method_select.data == 'output':
                add_method_data.time_start = form_add_method.output_daily_time.data
        elif method.method_type == 'Duration':
            if form_add_method.restart.data:
                add_method_data.duration_sec = 0
                add_method_data.duration_end = form_add_method.duration_end.data
            else:
                add_method_data.duration_sec = form_add_method.duration.data

        if form_add_method.method_select.data == 'setpoint':
            add_method_data.setpoint_start = form_add_method.setpoint_start.data
            add_method_data.setpoint_end = form_add_method.setpoint_end.data
        elif form_add_method.method_select.data == 'output':
            add_method_data.output_id = form_add_method.output_id.data
            add_method_data.output_state = form_add_method.output_state.data
            add_method_data.output_duration = form_add_method.output_duration.data

        db.session.add(add_method_data)
        db.session.commit()

        # Add line to method data list if not a output duration
        if form_add_method.method_select.data != 'output':
            method.method_order = add_display_order(
                display_order, add_method_data.unique_id)
            db.session.commit()

        if form_add_method.method_select.data == 'setpoint':
            if method.method_type == 'Date':
                flash(gettext("Added duration to method from %(st)s to "
                              "%(end)s", st=start_time, end=end_time),
                      "success")
            elif method.method_type == 'Daily':
                flash(gettext("Added duration to method from %(st)s to "
                              "%(end)s",
                              st=start_time.strftime('%H:%M:%S'),
                              end=end_time.strftime('%H:%M:%S')),
                      "success")
            elif method.method_type == 'Duration':
                if form_add_method.restart.data:
                    flash(gettext("Added method restart"), "success")
                else:
                    flash(gettext("Added duration to method for %(sec)s seconds",
                                  sec=form_add_method.duration.data), "success")
        elif form_add_method.method_select.data == 'output':
            if method.method_type == 'Date':
                flash(gettext("Added output modulation to method at start "
                              "time: %(tm)s", tm=start_time), "success")
            elif method.method_type == 'Daily':
                flash(gettext("Added output modulation to method at start "
                              "time: %(tm)s",
                              tm=start_time.strftime('%H:%M:%S')), "success")
            elif method.method_type == 'Duration':
                flash(gettext("Added output modulation to method at start "
                              "time: %(tm)s",
                              tm=form_add_method.duration.data), "success")

    except Exception as except_msg:
        logger.exception(1)
        error.append(except_msg)
    flash_success_errors(error, action, url_for('routes_method.method_list'))
Exemple #44
0
def method_mod(form_mod_method):
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['modify']['title'],
        controller=TRANSLATIONS['method']['title'])
    error = []

    method = Method.query.filter(
        Method.unique_id == form_mod_method.method_id.data).first()
    method_data = MethodData.query.filter(
        MethodData.unique_id == form_mod_method.method_data_id.data).first()
    display_order = csv_to_list_of_str(method.method_order)

    try:
        if form_mod_method.delete.data:
            delete_entry_with_id(MethodData,
                                 form_mod_method.method_data_id.data)
            if form_mod_method.method_select.data != 'output':
                method_order = Method.query.filter(
                    Method.unique_id == method.unique_id).first()
                display_order = csv_to_list_of_str(method_order.method_order)
                display_order.remove(method_data.unique_id)
                method_order.method_order = list_to_csv(display_order)
                db.session.commit()
            return 0

        if form_mod_method.rename.data:
            method.name = form_mod_method.name.data
            db.session.commit()
            return 0

        # Ensure data is valid
        if validate_method_data(form_mod_method, method):
            return 1

        if form_mod_method.method_select.data == 'setpoint':
            if method.method_type == 'Date':
                start_time = datetime.strptime(form_mod_method.time_start.data, '%Y-%m-%d %H:%M:%S')
                end_time = datetime.strptime(form_mod_method.time_end.data, '%Y-%m-%d %H:%M:%S')

                # Ensure the start time comes after the previous entry's end time
                # and the end time comes before the next entry's start time
                # method_id_set is the id given to all method entries, 'method_id', not 'id'
                previous_method = None
                next_method = None
                for index, each_order in enumerate(display_order):
                    if each_order == method_data.unique_id:
                        if len(display_order) > 1 and index > 0:
                            previous_method = MethodData.query.filter(
                                MethodData.unique_id == display_order[index-1]).first()
                        if len(display_order) > index+1:
                            next_method = MethodData.query.filter(
                                MethodData.unique_id == display_order[index+1]).first()

                if previous_method is not None and previous_method.time_end is not None:
                    previous_end_time = datetime.strptime(
                        previous_method.time_end, '%Y-%m-%d %H:%M:%S')
                    if previous_end_time is not None and start_time < previous_end_time:
                        error.append(
                            gettext("The entry start time (%(st)s) cannot "
                                    "overlap the previous entry's end time "
                                    "(%(et)s)",
                                    st=start_time, et=previous_end_time))

                if next_method is not None and next_method.time_start is not None:
                    next_start_time = datetime.strptime(
                        next_method.time_start, '%Y-%m-%d %H:%M:%S')
                    if next_start_time is not None and end_time > next_start_time:
                        error.append(
                            gettext("The entry end time (%(et)s) cannot "
                                    "overlap the next entry's start time "
                                    "(%(st)s)",
                                    et=end_time, st=next_start_time))

                method_data.time_start = start_time.strftime('%Y-%m-%d %H:%M:%S')
                method_data.time_end = end_time.strftime('%Y-%m-%d %H:%M:%S')

            elif method.method_type == 'Duration':
                if method_data.duration_sec == 0:
                    method_data.duration_end = form_mod_method.duration_end.data
                else:
                    method_data.duration_sec = form_mod_method.duration.data

            elif method.method_type == 'Daily':
                method_data.time_start = form_mod_method.daily_time_start.data
                method_data.time_end = form_mod_method.daily_time_end.data

            method_data.setpoint_start = form_mod_method.setpoint_start.data
            method_data.setpoint_end = form_mod_method.setpoint_end.data

        elif form_mod_method.method_select.data == 'output':
            if method.method_type == 'Date':
                method_data.time_start = form_mod_method.output_time.data
            elif method.method_type == 'Duration':
                method_data.duration_sec = form_mod_method.duration.data
            if form_mod_method.output_id.data == '':
                method_data.output_id = None
            else:
                method_data.output_id = form_mod_method.output_id.data
            method_data.output_state = form_mod_method.output_state.data
            method_data.output_duration = form_mod_method.output_duration.data

        elif method.method_type == 'DailySine':
            if form_mod_method.method_select.data == 'output':
                method_data.time_start = form_mod_method.output_time.data
                if form_mod_method.output_id.data == '':
                    method_data.output_id = None
                else:
                    method_data.output_id = form_mod_method.output_id.data
                method_data.output_state = form_mod_method.output_state.data
                method_data.output_duration = form_mod_method.output_duration.data

        if not error:
            db.session.commit()

    except Exception as except_msg:
        logger.exception(1)
        error.append(except_msg)
    flash_success_errors(error, action, url_for('routes_method.method_list'))