示例#1
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_int(method_order.method)
        method_order.method = add_display_order(display_order, new_method.id)
        db.session.commit()

        # For tables that require only one entry to configure,
        # create that single entry now with default values
        if new_method.method_type == 'DailySine':
            new_method_data = MethodData()
            new_method_data.method_id = new_method.id
            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
            db.session.add(new_method_data)
            db.session.commit()
        elif new_method.method_type == 'DailyBezier':
            new_method_data = MethodData()
            new_method_data.method_id = new_method.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()

        # Add new method data line id to method_data display order
        if new_method.method_type in ['DailyBezier', 'DailySine']:
            display_order = csv_to_list_of_int(new_method.method_order)
            method = Method.query.filter(Method.id == new_method.id).first()
            method.method_order = add_display_order(display_order,
                                                    new_method_data.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'))
示例#2
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)
示例#3
0
def math_add(form_add_math):
    action = u'{action} {controller}'.format(action=gettext(u"Add"),
                                             controller=gettext(u"Math"))
    error = []

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

        try:
            new_math.save()

            display_order = csv_to_list_of_int(DisplayOrder.query.first().math)
            DisplayOrder.query.first().math = add_display_order(
                display_order, new_math.id)
            db.session.commit()

            flash(
                gettext(
                    u"%(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('page_routes.page_input'))
    else:
        flash_form_errors(form_add_math)
示例#4
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
示例#5
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'))
示例#6
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
示例#7
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
示例#8
0
def timer_add(display_order, form_add_timer_base, form_add_timer):
    action = u'{action} {controller}'.format(action=gettext(u"Add"),
                                             controller=gettext(u"Timer"))
    error = []

    if not form_add_timer_base.validate():
        error.append("Correct the inputs that are invalid and resubmit")
        flash_form_errors(form_add_timer_base)
    if not form_add_timer.validate():
        error.append("Correct the inputs that are invalid and resubmit")
        flash_form_errors(form_add_timer)

    output = Output.query.filter(
        Output.unique_id == form_add_timer_base.relay_id.data).first()
    if (form_add_timer_base.timer_type.data == 'pwm_method'
            and output.relay_type != 'pwm'):
        error.append("PWM Method Timers require a PWM Output")
    elif (form_add_timer_base.timer_type.data != 'pwm_method'
          and output.relay_type == 'pwm'):
        error.append("Time and Duration Timers require a non-PWM Output")

    new_timer = Timer()
    new_timer.name = form_add_timer_base.name.data
    new_timer.relay_id = form_add_timer_base.relay_id.data
    new_timer.timer_type = form_add_timer_base.timer_type.data
    if form_add_timer_base.timer_type.data == 'time':
        new_timer.state = form_add_timer.state.data
        new_timer.time_start = form_add_timer.time_start.data
        new_timer.duration_on = form_add_timer.time_on_duration.data
        new_timer.duration_off = 0
    elif form_add_timer_base.timer_type.data == 'timespan':
        new_timer.state = form_add_timer.state.data
        new_timer.time_start = form_add_timer.time_start_duration.data
        new_timer.time_end = form_add_timer.time_end_duration.data
    elif form_add_timer_base.timer_type.data == 'duration':
        if (form_add_timer.duration_on.data <= 0
                or form_add_timer.duration_off.data <= 0):
            error.append(gettext(u"Durations must be greater than 0"))
        else:
            new_timer.duration_on = form_add_timer.duration_on.data
            new_timer.duration_off = form_add_timer.duration_off.data
    elif form_add_timer_base.timer_type.data == 'pwm_method':
        new_timer.method_id = form_add_timer.method_id.data
        new_timer.method_period = form_add_timer.method_period.data
    else:
        error.append("Not a recognized Timer type")

    if not error:
        try:
            new_timer.save()
            DisplayOrder.query.first().timer = add_display_order(
                display_order, new_timer.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('page_routes.page_timer'))
示例#9
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 form_add_func.func_type.data == 'pid':
                new_func = PID().save()
                if not error:
                    display_order = csv_to_list_of_int(
                        DisplayOrder.query.first().pid)
                    DisplayOrder.query.first().pid = add_display_order(
                        display_order, new_func.id)
                    db.session.commit()
            elif form_add_func.func_type.data in [
                    'conditional_measurement', 'conditional_output',
                    'conditional_edge', 'conditional_sunrise_sunset'
            ]:
                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_int(
                        DisplayOrder.query.first().conditional)
                    DisplayOrder.query.first().conditional = add_display_order(
                        display_order, new_func.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)
示例#10
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
示例#11
0
def output_add(form_add_relay):
    action = '{action} {controller}'.format(action=gettext("Add"),
                                            controller=gettext("Output"))
    error = []

    if is_int(form_add_relay.relay_quantity.data, check_range=[1, 20]):
        for _ in range(0, form_add_relay.relay_quantity.data):
            try:
                new_relay = Output()
                new_relay.relay_type = form_add_relay.relay_type.data
                if form_add_relay.relay_type.data == 'wired':
                    new_relay.on_at_start = False
                elif form_add_relay.relay_type.data == 'wireless_433MHz_pi_switch':
                    new_relay.protocol = 1
                    new_relay.bit_length = 25
                    new_relay.pulse_length = 189
                    new_relay.on_command = '22559'
                    new_relay.off_command = '22558'
                elif form_add_relay.relay_type.data == 'command':
                    new_relay.on_command = '/home/pi/script_on.sh'
                    new_relay.off_command = '/home/pi/script_off.sh'
                elif form_add_relay.relay_type.data == 'pwm':
                    new_relay.pwm_hertz = 22000
                    new_relay.pwm_library = 'pigpio_any'
                new_relay.save()
                display_order = csv_to_list_of_int(
                    DisplayOrder.query.first().relay)
                DisplayOrder.query.first().relay = add_display_order(
                    display_order, new_relay.id)
                db.session.commit()
                manipulate_output('Add', new_relay.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'))
示例#12
0
def pid_add(form_add_pid):
    action = u'{action} {controller}'.format(
        action=gettext(u"Add"),
        controller=gettext(u"PID"))
    error = []

    if form_add_pid.validate():
        for _ in range(0, form_add_pid.numberPIDs.data):
            try:
                new_pid = PID().save()
                display_order = csv_to_list_of_int(DisplayOrder.query.first().pid)
                DisplayOrder.query.first().pid = add_display_order(
                    display_order, new_pid.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('page_routes.page_pid'))
    else:
        flash_form_errors(form_add_pid)
示例#13
0
def math_add(form_add_math):
    action = '{action} {controller}'.format(
        action=gettext("Add"),
        controller=gettext("Math"))
    error = []

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

        if new_math.math_type == 'humidity':
            new_math.measure = 'humidity,humidity_ratio,specific_enthalpy,specific_volume'
            new_math.measure_units = '%'

        try:
            new_math.save()

            display_order = csv_to_list_of_int(
                DisplayOrder.query.first().math)
            DisplayOrder.query.first().math = add_display_order(
                display_order, new_math.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)
示例#14
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()

        try:
            from RPi import GPIO
            if GPIO.RPI_REVISION == 2 or GPIO.RPI_REVISION == 3:
                new_lcd.i2c_bus = 1
            else:
                new_lcd.i2c_bus = 0
        except:
            logger.error("RPi.GPIO and Raspberry Pi required for this action")

        lcd_id = form.lcd_type.data.split(",")[0]
        lcd_interface = form.lcd_type.data.split(",")[1]

        new_lcd.lcd_type = lcd_id
        new_lcd.interface = lcd_interface
        new_lcd.name = str(LCD_INFO[lcd_id]['name'])

        if lcd_id in ['128x32_pioled', '128x64_pioled'
                      ] and lcd_interface == 'I2C':
            new_lcd.location = '0x3c'
            new_lcd.pin_reset = 19
        elif lcd_id in ['16x2_generic', '20x4_generic'
                        ] and lcd_interface == 'I2C':
            new_lcd.location = '0x27'
        elif lcd_interface == 'SPI':
            new_lcd.pin_reset = 19
            new_lcd.pin_dc = 16
            new_lcd.spi_device = 0
            new_lcd.spi_bus = 0

        if lcd_id == '128x32_pioled':
            new_lcd.x_characters = 21
            new_lcd.y_lines = 4
        elif lcd_id == '128x64_pioled':
            new_lcd.x_characters = 21
            new_lcd.y_lines = 8
        elif lcd_id == '16x2_generic':
            new_lcd.x_characters = 16
            new_lcd.y_lines = 2
        elif lcd_id == '20x4_generic':
            new_lcd.x_characters = 20
            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
示例#15
0
def function_add(form_add_func):
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['add']['title'],
        controller=TRANSLATIONS['function']['title'])
    error = []

    dep_unmet, _ = return_dependencies(form_add_func.function_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_func.function_type.data,
                           dep=', '.join(list_unmet_deps)))

    new_func = None

    try:
        if form_add_func.function_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.function_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.function_type.data.startswith('trigger_'):
            new_func = Trigger()
            new_func.name = '{}'.format(
                FUNCTION_INFO[form_add_func.function_type.data]['name'])
            new_func.trigger_type = form_add_func.function_type.data
            new_func.save()
        elif form_add_func.function_type.data.startswith('function_'):
            new_func = Function()
            if form_add_func.function_type.data == 'function_spacer':
                new_func.name = 'Spacer'
            new_func.function_type = form_add_func.function_type.data
            new_func.save()
        elif form_add_func.function_type.data == '':
            error.append("Must select a function type")
        else:
            error.append("Unknown function type: '{}'".format(
                form_add_func.function_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'))

    if dep_unmet:
        return 1
示例#16
0
def output_add(form_add):
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['add']['title'],
        controller=TRANSLATIONS['output']['title'])
    error = []

    dict_outputs = parse_output_information()
    output_types_dict = output_types()

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

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

    if current_app.config['TESTING']:
        dep_unmet = False
    else:
        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 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:
                new_output = Output()

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

                new_output.name = "Name"
                new_output.output_type = output_type
                new_output.interface = output_interface

                #
                # Set default values for new input being added
                #

                # input add options
                if output_type in dict_outputs:

                    def dict_has_value(key):
                        if (key in dict_outputs[output_type] and
                                dict_outputs[output_type][key] is not None):
                            return True

                    #
                    # Interfacing options
                    #

                    if output_interface == 'I2C':
                        if dict_has_value('i2c_address_default'):
                            new_output.i2c_location = dict_outputs[
                                output_type]['i2c_address_default']
                        elif dict_has_value('i2c_location'):
                            new_output.i2c_location = dict_outputs[
                                output_type]['i2c_location'][
                                    0]  # First list entry

                    if output_interface == 'FTDI':
                        if dict_has_value('ftdi_location'):
                            new_output.ftdi_location = dict_outputs[
                                output_type]['ftdi_location']

                    if output_interface == 'UART':
                        if dict_has_value('uart_location'):
                            new_output.uart_location = dict_outputs[
                                output_type]['uart_location']

                    # UART options
                    if dict_has_value('uart_baud_rate'):
                        new_output.baud_rate = dict_outputs[output_type][
                            'uart_baud_rate']
                    if dict_has_value('pin_cs'):
                        new_output.pin_cs = dict_outputs[output_type]['pin_cs']
                    if dict_has_value('pin_miso'):
                        new_output.pin_miso = dict_outputs[output_type][
                            'pin_miso']
                    if dict_has_value('pin_mosi'):
                        new_output.pin_mosi = dict_outputs[output_type][
                            'pin_mosi']
                    if dict_has_value('pin_clock'):
                        new_output.pin_clock = dict_outputs[output_type][
                            'pin_clock']

                    # Bluetooth (BT) options
                    elif output_interface == 'BT':
                        if dict_has_value('bt_location'):
                            new_output.location = dict_outputs[output_type][
                                'bt_location']
                        if dict_has_value('bt_adapter'):
                            new_output.bt_adapter = dict_outputs[output_type][
                                'bt_adapter']

                    # GPIO options
                    elif output_interface == 'GPIO':
                        if dict_has_value('gpio_pin'):
                            new_output.pin = dict_outputs[output_type][
                                'gpio_pin']

                    # Custom location location
                    elif dict_has_value('location'):
                        new_output.location = dict_outputs[output_type][
                            'location']['options'][0][0]  # First entry in list

                #
                # Custom Options
                #

                list_options = []
                if 'custom_options' in dict_outputs[output_type]:
                    for each_option in dict_outputs[output_type][
                            '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_output.custom_options = ';'.join(list_options)

                if output_type in output_types_dict['pwm']:
                    new_output.pwm_hertz = 22000
                    new_output.pwm_library = 'pigpio_any'

                if output_type in output_types_dict['volume']:
                    new_output.output_mode = 'fastest_flow_rate'
                    new_output.flow_rate = 10
                    if output_type == 'atlas_ezo_pmp':
                        if output_interface == 'FTDI':
                            new_output.location = '/dev/ttyUSB0'
                        elif output_interface == 'I2C':
                            new_output.location = '0x67'
                            new_output.i2c_bus = 1
                        elif output_interface == 'UART':
                            new_output.location = '/dev/ttyAMA0'
                            new_output.baud_rate = 9600

                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'
                    new_output.force_command = True

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

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

                elif output_type == 'python':
                    new_output.on_command = """
import datetime
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
log_string = "{ts}: ID: {id}: ON".format(id=output_id, ts=timestamp)
self.logger.info(log_string)"""
                    new_output.off_command = """
import datetime
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
log_string = "{ts}: ID: {id}: OFF".format(id=output_id, ts=timestamp)
self.logger.info(log_string)"""
                    new_output.force_command = True

                elif output_type == 'python_pwm':
                    new_output.pwm_command = """
import datetime
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
log_string = "{ts}: ID: {id}: {dc} % Duty Cycle".format(
    dc=duty_cycle, id=output_id, ts=timestamp)
self.logger.info(log_string)"""

                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)

                    #
                    # If measurements defined in the Output Module
                    #

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

                    db.session.commit()

                    if not current_app.config['TESTING']:
                        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
示例#17
0
def input_add(form_add):
    action = '{action} {controller}'.format(
        action=gettext("Add"),
        controller=gettext("Input"))
    error = []

    if current_app.config['TESTING']:
        unmet_deps = False
    else:
        unmet_deps = return_dependencies(form_add.input_type.data)
        if unmet_deps:
            error.append("The {dev} device you're trying to add has unmet dependencies: {dep}".format(
                dev=form_add.input_type.data, dep=unmet_deps))

    if form_add.validate():
        new_sensor = Input()
        new_sensor.device = form_add.input_type.data

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

        if form_add.input_type.data in DEVICE_INFO:
            new_sensor.name = DEVICE_INFO[form_add.input_type.data]['name']
            new_sensor.measurements = ",".join(DEVICE_INFO[form_add.input_type.data]['measure'])
        else:
            new_sensor.name = 'Name'

        #
        # Set default values for new Inputs
        #

        # Linux command as sensor
        if form_add.input_type.data == 'LinuxCommand':
            new_sensor.cmd_command = 'shuf -i 50-70 -n 1'
            new_sensor.cmd_measurement = 'Condition'
            new_sensor.cmd_measurement_units = 'unit'

        # Server is up or down
        elif form_add.input_type.data in ['SERVER_PING',
                                          'SERVER_PORT_OPEN']:
            new_sensor.location = '127.0.0.1'
            new_sensor.period = 3600

        # Process monitors
        elif form_add.input_type.data == 'MYCODO_RAM':
            new_sensor.location = 'Mycodo_daemon'
        elif form_add.input_type.data == 'RPi':
            new_sensor.location = 'RPi'
        elif form_add.input_type.data == 'RPiCPULoad':
            new_sensor.location = 'RPi'
        elif form_add.input_type.data == 'RPiFreeSpace':
            new_sensor.location = '/'

        # Environmental Inputs

        # Electrical Conductivity
        elif form_add.input_type.data == 'ATLAS_EC_I2C':
            new_sensor.location = '0x01'
            new_sensor.interface = 'I2C'
        elif form_add.input_type.data == 'ATLAS_EC_UART':
            new_sensor.location = 'Tx/Rx'
            new_sensor.interface = 'UART'
            new_sensor.baud_rate = 9600
            if GPIO.RPI_INFO['P1_REVISION'] == 3:
                new_sensor.device_loc = "/dev/ttyS0"
            else:
                new_sensor.device_loc = "/dev/ttyAMA0"

        # Temperature
        if form_add.input_type.data == 'TMP006':
            new_sensor.location = '0x40'
        elif form_add.input_type.data == 'ATLAS_PT1000_I2C':
            new_sensor.interface = 'I2C'
            new_sensor.location = '0x66'
        elif form_add.input_type.data == 'ATLAS_PT1000_UART':
            new_sensor.location = 'Tx/Rx'
            new_sensor.interface = 'UART'
            new_sensor.baud_rate = 9600
            if GPIO.RPI_INFO['P1_REVISION'] == 3:
                new_sensor.device_loc = "/dev/ttyS0"
            else:
                new_sensor.device_loc = "/dev/ttyAMA0"
        elif form_add.input_type.data in ['MAX31855',
                                          'MAX31856',
                                          'MAX31865']:
            new_sensor.pin_cs = 8
            new_sensor.pin_miso = 9
            new_sensor.pin_mosi = 10
            new_sensor.pin_clock = 11
            if form_add.input_type.data == 'MAX31856':
                new_sensor.thermocouple_type = 'K'
            elif form_add.input_type.data == 'MAX31865':
                new_sensor.thermocouple_type = 'PT100'
                new_sensor.ref_ohm = 0

        # Temperature/Humidity
        elif form_add.input_type.data in ['AM2315', 'DHT11',
                                          'DHT22', 'HTU21D',
                                          'SHT1x_7x', 'SHT2x']:
            if form_add.input_type.data == 'AM2315':
                new_sensor.location = '0x5c'
            elif form_add.input_type.data == 'HTU21D':
                new_sensor.location = '0x40'
            elif form_add.input_type.data == 'SHT2x':
                new_sensor.location = '0x40'

        # Chirp moisture sensor
        elif form_add.input_type.data == 'CHIRP':
            new_sensor.location = '0x20'

        # CO2
        elif form_add.input_type.data == 'MH_Z16_I2C':
            new_sensor.location = '0x63'
            new_sensor.interface = 'I2C'
        elif form_add.input_type.data in ['K30_UART',
                                          'MH_Z16_UART',
                                          'MH_Z19_UART']:
            new_sensor.location = 'Tx/Rx'
            new_sensor.interface = 'UART'
            new_sensor.baud_rate = 9600
            if GPIO.RPI_INFO['P1_REVISION'] == 3:
                new_sensor.device_loc = "/dev/ttyS0"
            else:
                new_sensor.device_loc = "/dev/ttyAMA0"

        # pH
        elif form_add.input_type.data == 'ATLAS_PH_I2C':
            new_sensor.location = '0x63'
            new_sensor.interface = 'I2C'
        elif form_add.input_type.data == 'ATLAS_PH_UART':
            new_sensor.location = 'Tx/Rx'
            new_sensor.interface = 'UART'
            new_sensor.baud_rate = 9600
            if GPIO.RPI_INFO['P1_REVISION'] == 3:
                new_sensor.device_loc = "/dev/ttyS0"
            else:
                new_sensor.device_loc = "/dev/ttyAMA0"

        # Pressure
        if form_add.input_type.data == 'BME280':
            new_sensor.location = '0x76'
        elif form_add.input_type.data in ['BMP180', 'BMP280']:
            new_sensor.location = '0x77'

        # Light
        elif form_add.input_type.data in ['BH1750',
                                          'TSL2561',
                                          'TSL2591']:
            if form_add.input_type.data == 'BH1750':
                new_sensor.location = '0x23'
                new_sensor.resolution = 0  # 0=Low, 1=High, 2=High2
                new_sensor.sensitivity = 69
            elif form_add.input_type.data == 'TSL2561':
                new_sensor.location = '0x39'
            elif form_add.input_type.data == 'TSL2591':
                new_sensor.location = '0x29'

        # Analog to Digital Converters
        elif form_add.input_type.data in LIST_DEVICES_ADC:
            new_sensor.adc_measure = 'Condition'
            new_sensor.adc_measure_units = 'units'
            if form_add.input_type.data == 'ADS1x15':
                new_sensor.location = '0x48'
                new_sensor.adc_volts_min = -4.096
                new_sensor.adc_volts_max = 4.096
            elif form_add.input_type.data == 'MCP342x':
                new_sensor.location = '0x68'
                new_sensor.adc_volts_min = -2.048
                new_sensor.adc_volts_max = 2.048
            elif form_add.input_type.data == 'MCP3008':
                new_sensor.pin_cs = 8
                new_sensor.pin_miso = 9
                new_sensor.pin_mosi = 10
                new_sensor.pin_clock = 11
                new_sensor.adc_volts_min = 0
                new_sensor.adc_volts_max = 3.3

        try:
            if not error:
                new_sensor.save()

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

                flash(gettext(
                    "%(type)s Input with ID %(id)s (%(uuid)s) successfully added",
                    type=form_add.input_type.data,
                    id=new_sensor.id,
                    uuid=new_sensor.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 unmet_deps:
        return 1
示例#18
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'))
示例#19
0
def remote_host_add(form_setup, display_order):
    """
    Add a remote Mycodo to the Remote Admin Dashboard

    Authenticate a remote Mycodo install that will be used on this system's
    Remote Admin dashboard.
    The user name and password is sent, and if verified, the password hash
    and SSL certificate is sent back.
    The hash is used to authenticate and the certificate is used to perform
    a verified SSL, in all subsequent connections.
    """
    if not utils_general.user_has_permission('edit_settings'):
        return redirect(url_for('routes_general.home'))

    if form_setup.validate():
        try:
            # Send user and password to remote Mycodo to authenticate
            credentials = {
                'user': form_setup.username.data,
                'passw': form_setup.password.data
            }
            url = 'https://{}/newremote/'.format(form_setup.host.data)
            try:
                pw_check = requests.get(
                    url, params=credentials, verify=False).json()
            except Exception:
                return 1

            if 'status' not in pw_check:
                flash("Unknown response: {res}".format(res=pw_check), "error")
                return 1
            elif pw_check['status']:
                flash(pw_check['error_msg'], "error")
                return 1

            # Write remote certificate to file
            assure_path_exists(STORED_SSL_CERTIFICATE_PATH)
            public_key = '{path}/{file}'.format(
                path=STORED_SSL_CERTIFICATE_PATH,
                file='{add}_cert.pem'.format(add=form_setup.host.data))
            file_handler = open(public_key, 'w')
            file_handler.write(pw_check['certificate'])
            file_handler.close()

            new_remote_host = Remote()
            new_remote_host.host = form_setup.host.data
            new_remote_host.username = form_setup.username.data
            new_remote_host.password_hash = pw_check['hash']
            try:
                db.session.add(new_remote_host)
                db.session.commit()
                flash(gettext("Remote Host %(host)s with ID %(id)s "
                              "(%(uuid)s) successfully added",
                              host=form_setup.host.data,
                              id=new_remote_host.id,
                              uuid=new_remote_host.unique_id),
                      "success")

                DisplayOrder.query.first().remote_host = add_display_order(
                    display_order, new_remote_host.unique_id)
                db.session.commit()
            except sqlalchemy.exc.OperationalError as except_msg:
                flash(gettext("Error: %(err)s",
                              err='Remote Host Add: {msg}'.format(msg=except_msg)),
                      "error")
            except sqlalchemy.exc.IntegrityError as except_msg:
                flash(gettext("Error: %(err)s",
                              err='Remote Host Add: {msg}'.format(msg=except_msg)),
                      "error")
        except Exception as except_msg:
            flash(gettext("Error: %(err)s",
                          err='Remote Host Add: {msg}'.format(msg=except_msg)),
                  "error")
    else:
        flash_form_errors(form_setup)
示例#20
0
def input_add(form_add, request_form):
    action = '{action} {controller}'.format(action=gettext("Add"),
                                            controller=gettext("Input"))
    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'

        if ('measurements_list' in dict_inputs[input_name]
                and dict_inputs[input_name]['measurements_list'] != []):
            new_input.measurements = ",".join(
                dict_inputs[input_name]['measurements_list'])
        elif input_name == 'LinuxCommand':
            pass
        else:
            error.append("No measurements defined for this input.")

        #
        # Set default values for new input being added
        #

        # Set the default measurement values
        list_units = []
        if 'measurements_list' in dict_inputs[input_name]:
            for each_measurement in dict_inputs[input_name][
                    'measurements_list']:
                if each_measurement in MEASUREMENTS:
                    entry = '{measure},{unit}'.format(
                        measure=each_measurement,
                        unit=MEASUREMENTS[each_measurement]['units'][0])
                    list_units.append(entry)
                else:
                    error.append(
                        "Measurement '{measure}' not recognized.".format(
                            measure=each_measurement))
            new_input.convert_to_unit = ";".join(list_units)

        # 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('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_channel'):
                if len(dict_inputs[input_name]['adc_channel']) == 1:
                    new_input.adc_channel = dict_inputs[input_name][
                        'adc_channel'][0]
                elif len(dict_inputs[input_name]['adc_channel']) > 1:
                    new_input.adc_channel = dict_inputs[input_name][
                        'adc_channel'][0][0]
            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]
            if dict_has_value('adc_volts_min'):
                new_input.adc_volts_min = dict_inputs[input_name][
                    'adc_volts_min']
            if dict_has_value('adc_volts_max'):
                new_input.adc_volts_max = dict_inputs[input_name][
                    'adc_volts_max']
            if dict_has_value('adc_units_min'):
                new_input.adc_units_min = dict_inputs[input_name][
                    'adc_units_min']
            if dict_has_value('adc_units_max'):
                new_input.adc_units_max = dict_inputs[input_name][
                    'adc_units_max']
            if dict_has_value('adc_inverse_unit_scale'):
                new_input.adc_inverse_unit_scale = dict_inputs[input_name][
                    'adc_inverse_unit_scale']

            # 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']:
                option = '{id},{value}'.format(
                    id=each_option['id'], value=each_option['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()

                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
示例#21
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
示例#22
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
示例#23
0
def input_add(form_add_sensor):
    action = '{action} {controller}'.format(action=gettext("Add"),
                                            controller=gettext("Input"))
    error = []

    if form_add_sensor.validate():
        new_sensor = Input()
        new_sensor.device = form_add_sensor.input_type.data
        new_sensor.name = '{name} Input'.format(
            name=form_add_sensor.input_type.data)
        if GPIO.RPI_INFO['P1_REVISION'] in [2, 3]:
            new_sensor.i2c_bus = 1
            new_sensor.multiplexer_bus = 1
        else:
            new_sensor.i2c_bus = 0
            new_sensor.multiplexer_bus = 0

        # Linux command as sensor
        if form_add_sensor.input_type.data == 'LinuxCommand':
            new_sensor.cmd_command = 'shuf -i 50-70 -n 1'
            new_sensor.cmd_measurement = 'Condition'
            new_sensor.cmd_measurement_units = 'unit'

        # Server is up or down
        elif form_add_sensor.input_type.data in [
                'SERVER_PING', 'SERVER_PORT_OPEN'
        ]:
            new_sensor.measurements = 'boolean'
            new_sensor.location = '127.0.0.1'
            new_sensor.period = 3600

        # Process monitors
        elif form_add_sensor.input_type.data == 'MYCODO_RAM':
            new_sensor.measurements = 'disk_space'
            new_sensor.location = 'Mycodo_daemon'
        elif form_add_sensor.input_type.data == 'RPi':
            new_sensor.measurements = 'temperature'
            new_sensor.location = 'RPi'
        elif form_add_sensor.input_type.data == 'RPiCPULoad':
            new_sensor.measurements = 'cpu_load_1m,' \
                                      'cpu_load_5m,' \
                                      'cpu_load_15m'
            new_sensor.location = 'RPi'
        elif form_add_sensor.input_type.data == 'RPiFreeSpace':
            new_sensor.measurements = 'disk_space'
            new_sensor.location = '/'
        elif form_add_sensor.input_type.data == 'EDGE':
            new_sensor.measurements = 'edge'
        elif form_add_sensor.input_type.data == 'GPIO_STATE':
            new_sensor.measurements = 'gpio_state'

        # Signal measuremnt (PWM and RPM)
        elif form_add_sensor.input_type.data == 'SIGNAL_PWM':
            new_sensor.measurements = 'frequency,pulse_width,duty_cycle'
        elif form_add_sensor.input_type.data == 'SIGNAL_RPM':
            new_sensor.measurements = 'rpm'

        # Environmental Inputs
        # Temperature
        elif form_add_sensor.input_type.data in [
                'ATLAS_PT1000_I2C', 'ATLAS_PT1000_UART', 'DS18B20', 'TMP006'
        ]:
            new_sensor.measurements = 'temperature'
            if form_add_sensor.input_type.data == 'ATLAS_PT1000_I2C':
                new_sensor.interface = 'I2C'
                new_sensor.location = '0x66'
            elif form_add_sensor.input_type.data == 'ATLAS_PT1000_UART':
                new_sensor.location = 'Tx/Rx'
                new_sensor.interface = 'UART'
                new_sensor.baud_rate = 9600
                if GPIO.RPI_INFO['P1_REVISION'] == 3:
                    new_sensor.device_loc = "/dev/ttyS0"
                else:
                    new_sensor.device_loc = "/dev/ttyAMA0"
            elif form_add_sensor.input_type.data == 'TMP006':
                new_sensor.measurements = 'temperature_object,' \
                                          'temperature_die'
                new_sensor.location = '0x40'

        # Temperature/Humidity
        elif form_add_sensor.input_type.data in [
                'AM2315', 'DHT11', 'DHT22', 'HTU21D', 'SHT1x_7x', 'SHT2x'
        ]:
            new_sensor.measurements = 'temperature,humidity,dewpoint'
            if form_add_sensor.input_type.data == 'AM2315':
                new_sensor.location = '0x5c'
            elif form_add_sensor.input_type.data == 'HTU21D':
                new_sensor.location = '0x40'
            elif form_add_sensor.input_type.data == 'SHT2x':
                new_sensor.location = '0x40'

        # Chirp moisture sensor
        elif form_add_sensor.input_type.data == 'CHIRP':
            new_sensor.measurements = 'lux,moisture,temperature'
            new_sensor.location = '0x20'

        # CO2
        elif form_add_sensor.input_type.data == 'MH_Z16_I2C':
            new_sensor.measurements = 'co2'
            new_sensor.location = '0x63'
            new_sensor.interface = 'I2C'
        elif form_add_sensor.input_type.data in [
                'K30_UART', 'MH_Z16_UART', 'MH_Z19_UART'
        ]:
            new_sensor.measurements = 'co2'
            new_sensor.location = 'Tx/Rx'
            new_sensor.interface = 'UART'
            new_sensor.baud_rate = 9600
            if GPIO.RPI_INFO['P1_REVISION'] == 3:
                new_sensor.device_loc = "/dev/ttyS0"
            else:
                new_sensor.device_loc = "/dev/ttyAMA0"

        # pH
        elif form_add_sensor.input_type.data == 'ATLAS_PH_I2C':
            new_sensor.measurements = 'ph'
            new_sensor.location = '0x63'
            new_sensor.interface = 'I2C'
        elif form_add_sensor.input_type.data == 'ATLAS_PH_UART':
            new_sensor.measurements = 'ph'
            new_sensor.location = 'Tx/Rx'
            new_sensor.interface = 'UART'
            new_sensor.baud_rate = 9600
            if GPIO.RPI_INFO['P1_REVISION'] == 3:
                new_sensor.device_loc = "/dev/ttyS0"
            else:
                new_sensor.device_loc = "/dev/ttyAMA0"

        # Pressure
        elif form_add_sensor.input_type.data in ['BME280', 'BMP180', 'BMP280']:
            if form_add_sensor.input_type.data == 'BME280':
                new_sensor.measurements = 'temperature,humidity,' \
                                          'dewpoint,pressure,altitude'
                new_sensor.location = '0x76'
            elif form_add_sensor.input_type.data in ['BMP180', 'BMP280']:
                new_sensor.measurements = 'temperature,pressure,altitude'
                new_sensor.location = '0x77'

        # Light
        elif form_add_sensor.input_type.data in [
                'BH1750', 'TSL2561', 'TSL2591'
        ]:
            new_sensor.measurements = 'lux'
            if form_add_sensor.input_type.data == 'BH1750':
                new_sensor.location = '0x23'
                new_sensor.resolution = 0  # 0=Low, 1=High, 2=High2
                new_sensor.sensitivity = 69
            elif form_add_sensor.input_type.data == 'TSL2561':
                new_sensor.location = '0x39'
            elif form_add_sensor.input_type.data == 'TSL2591':
                new_sensor.location = '0x29'

        # Analog to Digital Converters
        elif form_add_sensor.input_type.data in ['ADS1x15', 'MCP342x']:
            new_sensor.measurements = 'voltage'
            if form_add_sensor.input_type.data == 'ADS1x15':
                new_sensor.location = '0x48'
                new_sensor.adc_volts_min = -4.096
                new_sensor.adc_volts_max = 4.096
            elif form_add_sensor.input_type.data == 'MCP342x':
                new_sensor.location = '0x68'
                new_sensor.adc_volts_min = -2.048
                new_sensor.adc_volts_max = 2.048

        try:
            new_sensor.save()

            display_order = csv_to_list_of_int(
                DisplayOrder.query.first().sensor)
            DisplayOrder.query.first().sensor = add_display_order(
                display_order, new_sensor.id)
            db.session.commit()

            flash(
                gettext(
                    "%(type)s Input with ID %(id)s (%(uuid)s) successfully added",
                    type=form_add_sensor.input_type.data,
                    id=new_sensor.id,
                    uuid=new_sensor.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_sensor)
示例#24
0
def dashboard_add(form_base, form_object, display_order):
    """
    Add an item to the dashboard

    Either Graph, Gauge, or Camera
    """
    action = '{action} {controller}'.format(action=gettext("Add"),
                                            controller=gettext("Dashboard"))
    error = []
    dashboard_type = ''

    new_graph = Dashboard()
    new_graph.name = form_base.name.data

    # Graph
    if (form_base.dashboard_type.data == 'graph'
            and (form_base.name.data and form_base.width.data
                 and form_base.height.data and form_object.xaxis_duration.data
                 and form_base.refresh_duration.data)):

        dashboard_type = 'Graph'
        error = graph_error_check(form_object, error)
        new_graph.graph_type = form_base.dashboard_type.data
        if form_object.math_ids.data:
            math_ids_joined = ";".join(form_object.math_ids.data)
            new_graph.math_ids = math_ids_joined
        if form_object.pid_ids.data:
            pid_ids_joined = ";".join(form_object.pid_ids.data)
            new_graph.pid_ids = pid_ids_joined
        if form_object.output_ids.data:
            output_ids_joined = ";".join(form_object.output_ids.data)
            new_graph.output_ids = output_ids_joined
        if form_object.input_ids.data:
            input_ids_joined = ";".join(form_object.input_ids.data)
            new_graph.input_ids_measurements = input_ids_joined
        new_graph.width = form_base.width.data
        new_graph.height = form_base.height.data
        new_graph.x_axis_duration = form_object.xaxis_duration.data
        new_graph.refresh_duration = form_base.refresh_duration.data
        new_graph.enable_auto_refresh = form_object.enable_auto_refresh.data
        new_graph.enable_xaxis_reset = form_object.enable_xaxis_reset.data
        new_graph.enable_title = form_object.enable_title.data
        new_graph.enable_navbar = form_object.enable_navbar.data
        new_graph.enable_rangeselect = form_object.enable_range.data
        new_graph.enable_export = form_object.enable_export.data
        new_graph.enable_graph_shift = form_object.enable_graph_shift.data
        new_graph.enable_manual_y_axis = form_object.enable_manual_y_axis.data

    # Gauge
    elif form_base.dashboard_type.data == 'gauge':

        dashboard_type = 'Gauge'
        error = gauge_error_check(form_object, error)
        new_graph.graph_type = form_object.gauge_type.data
        if form_object.gauge_type.data == 'gauge_solid':
            new_graph.range_colors = '20,#33CCFF;40,#55BF3B;60,#DDDF0D;80,#DF5353'
        elif form_object.gauge_type.data == 'gauge_angular':
            new_graph.range_colors = '0,25,#33CCFF;25,50,#55BF3B;50,75,#DDDF0D;75,100,#DF5353'
        new_graph.width = form_base.width.data
        new_graph.height = form_base.height.data
        new_graph.max_measure_age = form_object.max_measure_age.data
        new_graph.refresh_duration = form_base.refresh_duration.data
        new_graph.y_axis_min = form_object.y_axis_min.data
        new_graph.y_axis_max = form_object.y_axis_max.data
        new_graph.input_ids_measurements = form_object.input_ids.data
        new_graph.enable_timestamp = form_object.enable_timestamp.data

    # Measurement
    elif form_base.dashboard_type.data == 'measurement':

        dashboard_type = 'Measurement'
        error = measurement_error_check(form_object, error)
        new_graph.graph_type = 'measurement'
        new_graph.width = form_base.width.data
        new_graph.height = form_base.height.data
        new_graph.max_measure_age = form_object.max_measure_age.data
        new_graph.refresh_duration = form_base.refresh_duration.data
        new_graph.font_em_value = form_object.font_em_value.data
        new_graph.font_em_timestamp = form_object.font_em_timestamp.data
        new_graph.decimal_places = form_object.decimal_places.data
        new_graph.input_ids_measurements = form_object.measurement_id.data

    # Output
    elif form_base.dashboard_type.data == 'output':

        dashboard_type = 'Output'
        error = output_error_check(form_object, error)
        new_graph.graph_type = 'output'
        new_graph.width = form_base.width.data
        new_graph.height = form_base.height.data
        new_graph.max_measure_age = form_object.max_measure_age.data
        new_graph.refresh_duration = form_base.refresh_duration.data
        new_graph.font_em_value = form_object.font_em_value.data
        new_graph.font_em_timestamp = form_object.font_em_timestamp.data
        new_graph.enable_output_controls = form_object.enable_output_controls.data
        new_graph.decimal_places = form_object.decimal_places.data
        new_graph.output_ids = form_object.output_id.data

    # PID Control
    elif form_base.dashboard_type.data == 'pid_control':

        dashboard_type = 'PID Control'
        error = pid_error_check(form_object, error)
        new_graph.graph_type = 'pid_control'
        new_graph.width = form_base.width.data
        new_graph.height = form_base.height.data
        new_graph.max_measure_age = form_object.max_measure_age.data
        new_graph.refresh_duration = form_base.refresh_duration.data
        new_graph.font_em_value = form_object.font_em_value.data
        new_graph.font_em_timestamp = form_object.font_em_timestamp.data
        new_graph.decimal_places = form_object.decimal_places.data
        new_graph.show_pid_info = form_object.show_pid_info.data
        new_graph.show_set_setpoint = form_object.show_set_setpoint.data
        new_graph.pid_ids = form_object.pid_id.data

    # Camera
    elif (form_base.dashboard_type.data == 'camera'
          and form_object.camera_id.data):

        dashboard_type = 'Camera'
        new_graph.graph_type = form_base.dashboard_type.data
        new_graph.width = form_base.width.data
        new_graph.height = form_base.height.data
        new_graph.refresh_duration = form_base.refresh_duration.data
        new_graph.camera_max_age = form_object.camera_max_age.data
        new_graph.camera_id = form_object.camera_id.data
        new_graph.camera_image_type = form_object.camera_image_type.data
    else:
        flash_form_errors(form_base)
        return

    try:
        if not error:
            new_graph.save()
            flash(
                gettext("{dev} with ID %(id)s successfully added".format(
                    dev=dashboard_type),
                        id=new_graph.id), "success")
            DisplayOrder.query.first().dashboard = add_display_order(
                display_order, new_graph.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_dashboard'))
示例#25
0
def dashboard_add(form_base, form_object, display_order):
    """
    Add an item to the dashboard

    Either Graph, Gauge, or Camera
    """
    action = '{action} {controller}'.format(action=gettext("Add"),
                                            controller=gettext("Dashboard"))
    error = []

    new_graph = Dashboard()
    new_graph.name = form_base.name.data

    # Graph
    if (form_base.dashboard_type.data == 'graph' and
        (form_base.name.data and form_object.width.data
         and form_object.height.data and form_object.xaxis_duration.data
         and form_object.refresh_duration.data)):

        error = graph_error_check(form_object, error)

        new_graph.graph_type = form_base.dashboard_type.data

        if form_object.math_ids.data:
            math_ids_joined = ";".join(form_object.math_ids.data)
            new_graph.math_ids = math_ids_joined
        if form_object.pid_ids.data:
            pid_ids_joined = ";".join(form_object.pid_ids.data)
            new_graph.pid_ids = pid_ids_joined
        if form_object.relay_ids.data:
            relay_ids_joined = ";".join(form_object.relay_ids.data)
            new_graph.relay_ids = relay_ids_joined
        if form_object.sensor_ids.data:
            sensor_ids_joined = ";".join(form_object.sensor_ids.data)
            new_graph.sensor_ids_measurements = sensor_ids_joined
        new_graph.width = form_object.width.data
        new_graph.height = form_object.height.data
        new_graph.x_axis_duration = form_object.xaxis_duration.data
        new_graph.refresh_duration = form_object.refresh_duration.data
        new_graph.enable_auto_refresh = form_object.enable_auto_refresh.data
        new_graph.enable_xaxis_reset = form_object.enable_xaxis_reset.data
        new_graph.enable_title = form_object.enable_title.data
        new_graph.enable_navbar = form_object.enable_navbar.data
        new_graph.enable_rangeselect = form_object.enable_range.data
        new_graph.enable_export = form_object.enable_export.data
        new_graph.enable_graph_shift = form_object.enable_graph_shift.data
        new_graph.enable_manual_y_axis = form_object.enable_manual_y_axis.data

        try:
            if not error:
                new_graph.save()
                flash(
                    gettext("Graph with ID %(id)s successfully added",
                            id=new_graph.id), "success")

                DisplayOrder.query.first().graph = add_display_order(
                    display_order, new_graph.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)

    # Gauge
    elif (form_base.dashboard_type.data == 'gauge'
          and form_object.sensor_ids.data):

        error = gauge_error_check(form_object, error)

        new_graph.graph_type = form_object.gauge_type.data

        if form_object.gauge_type.data == 'gauge_solid':
            new_graph.range_colors = '0.2,#33CCFF;0.4,#55BF3B;0.6,#DDDF0D;0.8,#DF5353'
        elif form_object.gauge_type.data == 'gauge_angular':
            new_graph.range_colors = '0,25,#33CCFF;25,50,#55BF3B;50,75,#DDDF0D;75,100,#DF5353'
        new_graph.width = form_object.width.data
        new_graph.height = form_object.height.data
        new_graph.max_measure_age = form_object.max_measure_age.data
        new_graph.refresh_duration = form_object.refresh_duration.data
        new_graph.y_axis_min = form_object.y_axis_min.data
        new_graph.y_axis_max = form_object.y_axis_max.data
        new_graph.sensor_ids_measurements = form_object.sensor_ids.data[0]
        new_graph.enable_timestamp = form_object.enable_timestamp.data
        try:
            if not error:
                new_graph.save()
                flash(
                    gettext("Gauge with ID %(id)s successfully added",
                            id=new_graph.id), "success")

                DisplayOrder.query.first().graph = add_display_order(
                    display_order, new_graph.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)

    # Camera
    elif (form_base.dashboard_type.data == 'camera'
          and form_object.camera_id.data):

        new_graph.graph_type = form_base.dashboard_type.data
        new_graph.width = form_object.width.data
        new_graph.height = form_object.height.data
        new_graph.refresh_duration = form_object.refresh_duration.data
        new_graph.camera_max_age = form_object.camera_max_age.data
        new_graph.camera_id = form_object.camera_id.data
        new_graph.camera_image_type = form_object.camera_image_type.data
        try:
            if not error:
                new_graph.save()
                flash(
                    gettext("Camera with ID %(id)s successfully added",
                            id=new_graph.id), "success")

                DisplayOrder.query.first().graph = add_display_order(
                    display_order, new_graph.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)

    else:
        flash_form_errors(form_base)
        return

    flash_success_errors(error, action, url_for('routes_page.page_dashboard'))
示例#26
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'))
示例#27
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
示例#28
0
def function_add(form_add_func):
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['add']['title'],
        controller=TRANSLATIONS['function']['title'])
    error = []

    function_name = form_add_func.function_type.data

    dict_controllers = parse_function_information()

    if current_app.config['TESTING']:
        dep_unmet = False
    else:
        dep_unmet, _ = return_dependencies(function_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=function_name,
                                             dep=', '.join(list_unmet_deps)))

    new_func = None

    try:
        if function_name == 'conditional_conditional':
            new_func = Conditional()
            new_func.conditional_statement = '''
# Example code for learning how to use a Conditional. See the manual for more information.

self.logger.info("This INFO log entry will appear in the Daemon Log")
self.logger.error("This ERROR log entry will appear in the Daemon Log")

# Replace "asdf1234" with a Condition ID
measurement = self.condition("{asdf1234}")
self.logger.info("Check this measurement in the Daemon Log. The value is {val}".format(val=measurement))

if measurement is not None:  # If a measurement exists
    self.message += "This message appears in email alerts and notes.\\n"

    if measurement < 23:  # If the measurement is less than 23
        self.message += "Measurement is too Low! Measurement is {meas}\\n".format(meas=measurement)
        self.run_all_actions(message=self.message)  # Run all actions sequentially

    elif measurement > 27:  # Else If the measurement is greater than 27
        self.message += "Measurement is too High! Measurement is {meas}\\n".format(meas=measurement)
        # Replace "qwer5678" with an Action ID
        self.run_action("{qwer5678}", message=self.message)  # Run a single specific Action'''

            if not error:
                new_func.save()
                save_conditional_code(error,
                                      new_func.conditional_statement,
                                      new_func.unique_id,
                                      ConditionalConditions.query.all(),
                                      Actions.query.all(),
                                      test=False)

        elif function_name == 'pid_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
                if not error:
                    new_measurement.save()

        elif function_name in [
                'trigger_edge', 'trigger_output', 'trigger_output_pwm',
                'trigger_timer_daily_time_point',
                'trigger_timer_daily_time_span', 'trigger_timer_duration',
                'trigger_infrared_remote_input', 'trigger_run_pwm_method',
                'trigger_sunrise_sunset'
        ]:
            new_func = Trigger()
            new_func.name = '{}'.format(FUNCTION_INFO[function_name]['name'])
            new_func.trigger_type = function_name
            if not error:
                new_func.save()

        elif function_name in ['function_spacer', 'function_actions']:
            new_func = Function()
            if function_name == 'function_spacer':
                new_func.name = 'Spacer'
            new_func.function_type = function_name
            if not error:
                new_func.save()

        elif function_name in dict_controllers:
            # Custom Function Controller
            new_func = CustomController()
            new_func.device = function_name

            if 'function_name' in dict_controllers[function_name]:
                new_func.name = dict_controllers[function_name][
                    'function_name']
            else:
                new_func.name = 'Function Name'

            # TODO: Switch to JSON function
            list_options = []
            if 'custom_options' in dict_controllers[function_name]:
                for each_option in dict_controllers[function_name][
                        'custom_options']:
                    if 'id' not in each_option:
                        continue

                    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_func.custom_options = ';'.join(list_options)
            if not error:
                new_func.save()

        elif function_name == '':
            error.append("Must select a function type")
        else:
            error.append("Unknown function type: '{}'".format(function_name))

        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'))

    if dep_unmet:
        return 1
示例#29
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'))
示例#30
0
def graph_add(form_add, display_order):
    action = u'{action} {controller}'.format(action=gettext(u"Add"),
                                             controller=gettext(u"Graph"))
    error = []
    new_graph = Graph()

    if (form_add.graph_type.data == 'graph' and
        (form_add.name.data and form_add.width.data and form_add.height.data
         and form_add.xaxis_duration.data and form_add.refresh_duration.data)):
        new_graph.graph_type = form_add.graph_type.data
        new_graph.name = form_add.name.data
        if form_add.math_ids.data:
            math_ids_joined = ";".join(form_add.math_ids.data)
            new_graph.math_ids = math_ids_joined
        if form_add.pid_ids.data:
            pid_ids_joined = ";".join(form_add.pid_ids.data)
            new_graph.pid_ids = pid_ids_joined
        if form_add.relay_ids.data:
            relay_ids_joined = ";".join(form_add.relay_ids.data)
            new_graph.relay_ids = relay_ids_joined
        if form_add.sensor_ids.data:
            sensor_ids_joined = ";".join(form_add.sensor_ids.data)
            new_graph.sensor_ids_measurements = sensor_ids_joined
        new_graph.width = form_add.width.data
        new_graph.height = form_add.height.data
        new_graph.x_axis_duration = form_add.xaxis_duration.data
        new_graph.refresh_duration = form_add.refresh_duration.data
        new_graph.enable_auto_refresh = form_add.enable_auto_refresh.data
        new_graph.enable_xaxis_reset = form_add.enable_xaxis_reset.data
        new_graph.enable_title = form_add.enable_title.data
        new_graph.enable_navbar = form_add.enable_navbar.data
        new_graph.enable_rangeselect = form_add.enable_range.data
        new_graph.enable_export = form_add.enable_export.data
        try:
            new_graph.save()
            flash(
                gettext(u"Graph with ID %(id)s successfully added",
                        id=new_graph.id), "success")

            DisplayOrder.query.first().graph = add_display_order(
                display_order, new_graph.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)
    elif (form_add.graph_type.data in ['gauge_angular', 'gauge_solid']
          and form_add.sensor_ids.data):
        if form_add.graph_type.data == 'gauge_solid':
            new_graph.range_colors = '0.2,#33CCFF;0.4,#55BF3B;0.6,#DDDF0D;0.8,#DF5353'
        elif form_add.graph_type.data == 'gauge_angular':
            new_graph.range_colors = '0,25,#33CCFF;25,50,#55BF3B;50,75,#DDDF0D;75,100,#DF5353'
        new_graph.graph_type = form_add.graph_type.data
        new_graph.name = form_add.name.data
        new_graph.width = form_add.width.data
        new_graph.height = form_add.height.data
        new_graph.max_measure_age = form_add.max_measure_age.data
        new_graph.refresh_duration = form_add.refresh_duration.data
        new_graph.y_axis_min = form_add.y_axis_min.data
        new_graph.y_axis_max = form_add.y_axis_max.data
        new_graph.sensor_ids_measurements = form_add.sensor_ids.data[0]
        try:
            new_graph.save()
            flash(
                gettext(u"Graph with ID %(id)s successfully added",
                        id=new_graph.id), "success")

            DisplayOrder.query.first().graph = add_display_order(
                display_order, new_graph.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)
    else:
        flash_form_errors(form_add)
        return

    flash_success_errors(error, action, url_for('page_routes.page_graph'))
示例#31
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
示例#32
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 = []

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

    try:
        # Create method
        new_method = Method()
        new_method.name = form_create_method.name.data
        new_method.method_type = form_create_method.method_type.data

        if not error:
            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

            if not error:
                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()
    except Exception as except_msg:
        error.append(except_msg)

    flash_success_errors(error, action, url_for('routes_method.method_list'))

    if dep_unmet:
        return 1
示例#33
0
def output_add(form_add, request_form):
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['add']['title'],
        controller=TRANSLATIONS['output']['title'])
    error = []

    dict_outputs = parse_output_information()

    if current_app.config['TESTING']:
        dep_unmet = False
    else:
        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.split(',')[0], dep=', '.join(list_unmet_deps)))

    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 form_add.output_type.data.count(',') == 1:
        output_type = form_add.output_type.data.split(',')[0]
        output_interface = form_add.output_type.data.split(',')[1]
    else:
        output_type = ''
        output_interface = ''
        error.append("Invalid output string (must be a comma-separated string)")

    if not error:
        for _ in range(0, form_add.output_quantity.data):
            try:
                new_output = Output()
                try:
                    from RPi import GPIO
                    if GPIO.RPI_INFO['P1_REVISION'] == 1:
                        new_output.i2c_bus = 0
                    else:
                        new_output.i2c_bus = 1
                except:
                    logger.error(
                        "RPi.GPIO and Raspberry Pi required for this action")

                new_output.name = "Name"
                new_output.output_type = output_type
                new_output.interface = output_interface

                #
                # Set default values for new input being added
                #

                # input add options
                if output_type in dict_outputs:
                    def dict_has_value(key):
                        if (key in dict_outputs[output_type] and
                                dict_outputs[output_type][key] is not None):
                            return True

                    #
                    # Interfacing options
                    #

                    if output_interface == 'I2C':
                        if dict_has_value('i2c_address_default'):
                            new_output.i2c_location = dict_outputs[output_type]['i2c_address_default']
                        elif dict_has_value('i2c_location'):
                            new_output.i2c_location = dict_outputs[output_type]['i2c_location'][0]  # First list entry

                    if output_interface == 'FTDI':
                        if dict_has_value('ftdi_location'):
                            new_output.ftdi_location = dict_outputs[output_type]['ftdi_location']

                    if output_interface == 'UART':
                        if dict_has_value('uart_location'):
                            new_output.uart_location = dict_outputs[output_type]['uart_location']

                    # UART options
                    if dict_has_value('uart_baud_rate'):
                        new_output.baud_rate = dict_outputs[output_type]['uart_baud_rate']
                    if dict_has_value('pin_cs'):
                        new_output.pin_cs = dict_outputs[output_type]['pin_cs']
                    if dict_has_value('pin_miso'):
                        new_output.pin_miso = dict_outputs[output_type]['pin_miso']
                    if dict_has_value('pin_mosi'):
                        new_output.pin_mosi = dict_outputs[output_type]['pin_mosi']
                    if dict_has_value('pin_clock'):
                        new_output.pin_clock = dict_outputs[output_type]['pin_clock']

                    # Bluetooth (BT) options
                    elif output_interface == 'BT':
                        if dict_has_value('bt_location'):
                            new_output.location = dict_outputs[output_type]['bt_location']
                        if dict_has_value('bt_adapter'):
                            new_output.bt_adapter = dict_outputs[output_type]['bt_adapter']

                    # GPIO options
                    elif output_interface == 'GPIO':
                        if dict_has_value('gpio_pin'):
                            new_output.pin = dict_outputs[output_type]['gpio_pin']

                    # Custom location location
                    elif dict_has_value('location'):
                        new_output.location = dict_outputs[output_type]['location']['options'][0][0]  # First entry in list

                # Generate string to save from custom options
                error, custom_options = custom_options_return_json(
                    error, dict_outputs, request_form, device=output_type, use_defaults=True)
                new_output.custom_options = custom_options

                #
                # Execute at Creation
                #

                new_output.unique_id = set_uuid()

                if 'execute_at_creation' in dict_outputs[output_type] and not current_app.config['TESTING']:
                    dict_outputs[output_type]['execute_at_creation'](
                        new_output, dict_outputs[output_type])

                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()

                    #
                    # If measurements defined in the Output Module
                    #

                    if ('measurements_dict' in dict_outputs[output_type] and
                            dict_outputs[output_type]['measurements_dict'] != []):
                        for each_measurement in dict_outputs[output_type]['measurements_dict']:
                            measure_info = dict_outputs[output_type]['measurements_dict'][each_measurement]
                            new_measurement = DeviceMeasurements()
                            if 'name' in measure_info:
                                new_measurement.name = measure_info['name']
                            new_measurement.device_id = new_output.unique_id
                            new_measurement.measurement = measure_info['measurement']
                            new_measurement.unit = measure_info['unit']
                            new_measurement.channel = each_measurement
                            new_measurement.save()

                    for each_channel, channel_info in dict_outputs[output_type]['channels_dict'].items():
                        new_channel = OutputChannel()
                        new_channel.channel = each_channel
                        new_channel.output_id = new_output.unique_id

                        # Generate string to save from custom options
                        error, custom_options = custom_channel_options_return_json(
                            error, dict_outputs, request_form,
                            new_output.unique_id, each_channel,
                            device=output_type, use_defaults=True)
                        new_channel.custom_options = custom_options

                        new_channel.save()

                    # Refresh output settings
                    if not current_app.config['TESTING']:
                        manipulate_output('Add', new_output.unique_id)

                    flash(gettext("{dev} with ID %(id)s successfully added".format(
                        dev=dict_outputs[output_type]['output_name']), id=new_output.id),
                        "success")
            except sqlalchemy.exc.OperationalError as except_msg:
                error.append(except_msg)
            except sqlalchemy.exc.IntegrityError as except_msg:
                error.append(except_msg)
            except Exception:
                logger.exception(1)

    return dep_unmet
示例#34
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'))
示例#35
0
def dashboard_add(form_base, form_object, display_order):
    """
    Add an item to the dashboard

    Either Graph, Gauge, or Camera
    """
    action = '{action} {controller}'.format(
        action=TRANSLATIONS['add']['title'],
        controller=TRANSLATIONS['dashboard']['title'])
    error = []

    new_graph = Dashboard()
    new_graph.name = form_base.name.data

    # Graph
    if (form_base.dashboard_type.data == 'graph' and
            (form_base.name.data and
             form_base.width.data and
             form_base.height.data and
             form_object.xaxis_duration.data and
             form_base.refresh_duration.data)):

        dashboard_type = 'Graph'
        error = graph_error_check(form_object, error)
        new_graph.graph_type = form_base.dashboard_type.data
        if form_object.math_ids.data:
            new_graph.math_ids = ";".join(form_object.math_ids.data)
        if form_object.pid_ids.data:
            new_graph.pid_ids = ";".join(form_object.pid_ids.data)
        if form_object.output_ids.data:
            new_graph.output_ids = ";".join(form_object.output_ids.data)
        if form_object.input_ids.data:
            new_graph.input_ids_measurements = ";".join(form_object.input_ids.data)
        if form_object.note_tag_ids.data:
            new_graph.note_tag_ids = ";".join(form_object.note_tag_ids.data)
        new_graph.width = form_base.width.data
        new_graph.height = form_base.height.data
        new_graph.x_axis_duration = form_object.xaxis_duration.data
        new_graph.refresh_duration = form_base.refresh_duration.data
        new_graph.enable_auto_refresh = form_object.enable_auto_refresh.data
        new_graph.enable_xaxis_reset = form_object.enable_xaxis_reset.data
        new_graph.enable_title = form_object.enable_title.data
        new_graph.enable_navbar = form_object.enable_navbar.data
        new_graph.enable_rangeselect = form_object.enable_range.data
        new_graph.enable_export = form_object.enable_export.data
        new_graph.enable_graph_shift = form_object.enable_graph_shift.data
        new_graph.enable_manual_y_axis = form_object.enable_manual_y_axis.data

    # Gauge
    elif form_base.dashboard_type.data == 'gauge':

        dashboard_type = 'Gauge'
        error = gauge_error_check(form_object, error)
        new_graph.graph_type = form_object.gauge_type.data
        if form_object.gauge_type.data == 'gauge_solid':
            new_graph.range_colors = '20,#33CCFF;40,#55BF3B;60,#DDDF0D;80,#DF5353'
        elif form_object.gauge_type.data == 'gauge_angular':
            new_graph.range_colors = '0,25,#33CCFF;25,50,#55BF3B;50,75,#DDDF0D;75,100,#DF5353'
        new_graph.width = form_base.width.data
        new_graph.height = form_base.height.data
        new_graph.max_measure_age = form_object.max_measure_age.data
        new_graph.refresh_duration = form_base.refresh_duration.data
        new_graph.y_axis_min = form_object.y_axis_min.data
        new_graph.y_axis_max = form_object.y_axis_max.data
        new_graph.input_ids_measurements = form_object.input_ids.data
        new_graph.enable_timestamp = form_object.enable_timestamp.data

    # Indicator
    elif form_base.dashboard_type.data == 'indicator':

        dashboard_type = 'Indicator'
        error = measurement_error_check(form_object, error)
        new_graph.graph_type = 'indicator'
        new_graph.width = form_base.width.data
        new_graph.height = form_base.height.data
        new_graph.max_measure_age = form_object.max_measure_age.data
        new_graph.refresh_duration = form_base.refresh_duration.data
        new_graph.font_em_timestamp = form_object.font_em_timestamp.data
        new_graph.input_ids_measurements = form_object.measurement_id.data

    # Measurement
    elif form_base.dashboard_type.data == 'measurement':

        dashboard_type = 'Measurement'
        error = measurement_error_check(form_object, error)
        new_graph.graph_type = 'measurement'
        new_graph.width = form_base.width.data
        new_graph.height = form_base.height.data
        new_graph.max_measure_age = form_object.max_measure_age.data
        new_graph.refresh_duration = form_base.refresh_duration.data
        new_graph.font_em_value = form_object.font_em_value.data
        new_graph.font_em_timestamp = form_object.font_em_timestamp.data
        new_graph.decimal_places = form_object.decimal_places.data
        new_graph.input_ids_measurements = form_object.measurement_id.data

    # Output
    elif form_base.dashboard_type.data == 'output':

        dashboard_type = 'Output'
        error = output_error_check(form_object, error)
        new_graph.graph_type = 'output'
        new_graph.width = form_base.width.data
        new_graph.height = form_base.height.data
        new_graph.max_measure_age = form_object.max_measure_age.data
        new_graph.refresh_duration = form_base.refresh_duration.data
        new_graph.font_em_value = form_object.font_em_value.data
        new_graph.font_em_timestamp = form_object.font_em_timestamp.data
        new_graph.enable_output_controls = form_object.enable_output_controls.data
        new_graph.decimal_places = form_object.decimal_places.data
        new_graph.output_ids = form_object.output_id.data

    # PID Control
    elif form_base.dashboard_type.data == 'pid_control':

        dashboard_type = 'PID Control'
        error = pid_error_check(form_object, error)
        new_graph.graph_type = 'pid_control'
        new_graph.width = form_base.width.data
        new_graph.height = form_base.height.data
        new_graph.max_measure_age = form_object.max_measure_age.data
        new_graph.refresh_duration = form_base.refresh_duration.data
        new_graph.font_em_value = form_object.font_em_value.data
        new_graph.font_em_timestamp = form_object.font_em_timestamp.data
        new_graph.decimal_places = form_object.decimal_places.data
        new_graph.show_pid_info = form_object.show_pid_info.data
        new_graph.show_set_setpoint = form_object.show_set_setpoint.data
        new_graph.pid_ids = form_object.pid_id.data

    # Camera
    elif (form_base.dashboard_type.data == 'camera' and
          form_object.camera_id.data):

        dashboard_type = 'Camera'
        new_graph.graph_type = form_base.dashboard_type.data
        new_graph.width = form_base.width.data
        new_graph.height = form_base.height.data
        new_graph.refresh_duration = form_base.refresh_duration.data
        new_graph.camera_max_age = form_object.camera_max_age.data
        new_graph.camera_id = form_object.camera_id.data
        new_graph.camera_image_type = form_object.camera_image_type.data
    else:
        flash_form_errors(form_base)
        return

    try:
        if not error:
            new_graph.save()
            flash(gettext(
                "{dev} with ID %(id)s successfully added".format(dev=dashboard_type),
                id=new_graph.id),
                "success")
            DisplayOrder.query.first().dashboard = add_display_order(
                display_order, new_graph.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_dashboard'))
示例#36
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
示例#37
0
def math_add(form_add_math):
    action = '{action} {controller}'.format(action=gettext("Add"),
                                            controller=gettext("Math"))
    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 = ''
        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'])

        # Set the default measurement values
        list_units = []
        for each_measurement in MATH_INFO[
                form_add_math.math_type.data]['measure']:
            if each_measurement in MEASUREMENTS:
                entry = '{measure},{unit}'.format(
                    measure=each_measurement,
                    unit=MEASUREMENTS[each_measurement]['units'][0])
                list_units.append(entry)
        new_math.measure_units = ";".join(list_units)

        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 dep_unmet:
        return 1