コード例 #1
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
コード例 #2
0
ファイル: utils_input.py プロジェクト: mo-dgc/Mycodo
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
コード例 #3
0
ファイル: utils_input.py プロジェクト: rosaLux161/Mycodo
def input_add(form_add):
    messages = {"success": [], "info": [], "warning": [], "error": []}
    new_input_id = None
    list_unmet_deps = []
    dep_name = None
    dep_message = ''

    dict_inputs = parse_input_information()

    # only one comma should be in the input_type string
    if form_add.input_type.data.count(',') > 1:
        messages["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 = ''
        messages["error"].append(
            "Invalid input string (must be a comma-separated string)")

    if not current_app.config['TESTING']:
        dep_unmet, _, dep_message = return_dependencies(input_name)
        if dep_unmet:
            for each_dep in dep_unmet:
                list_unmet_deps.append(each_dep[3])
            messages["error"].append(
                f"{input_name} has unmet dependencies. They must be installed before the Input can be added."
            )
            if input_name in dict_inputs:
                dep_name = dict_inputs[input_name]['input_name']
            else:
                messages["error"].append(f"Input not found: {input_name}")

            return messages, dep_name, list_unmet_deps, dep_message, None

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

        if input_interface:
            new_input.interface = input_interface

        new_input.i2c_bus = 1

        if 'input_name_short' in dict_inputs[input_name]:
            new_input.name = dict_inputs[input_name]['input_name_short']
        elif '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'):
                    if not re.match(
                            "[0-9a-fA-F]{2}([:]?)[0-9a-fA-F]{2}(\\1[0-9a-fA-F]{2}){4}$",
                            dict_inputs[input_name]['bt_location']):
                        messages["error"].append(
                            "Please specify device MAC-Address in format AA:BB:CC:DD:EE:FF"
                        )
                    else:
                        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
        messages["error"], custom_options = custom_options_return_json(
            messages["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']):
            messages["error"], new_input = dict_inputs[
                new_input.device]['execute_at_creation'](
                    messages["error"], new_input,
                    dict_inputs[new_input.device])

        try:
            if not messages["error"]:
                new_input.save()
                new_input_id = new_input.unique_id

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

                if 'channels_dict' in dict_inputs[new_input.device]:
                    for each_channel, channel_info in dict_inputs[
                            new_input.device]['channels_dict'].items():
                        new_channel = InputChannel()
                        new_channel.channel = each_channel
                        new_channel.input_id = new_input.unique_id

                        # Generate string to save from custom options
                        messages[
                            "error"], custom_options = custom_channel_options_return_json(
                                messages["error"],
                                dict_inputs,
                                None,
                                new_input.unique_id,
                                each_channel,
                                device=new_input.device,
                                use_defaults=True)
                        new_channel.custom_options = custom_options

                        new_channel.save()

                messages["success"].append(
                    f"{TRANSLATIONS['add']['title']} {TRANSLATIONS['input']['title']}"
                )
        except sqlalchemy.exc.OperationalError as except_msg:
            messages["error"].append(except_msg)
        except sqlalchemy.exc.IntegrityError as except_msg:
            messages["error"].append(except_msg)

    else:
        for field, errors in form_add.errors.items():
            for error in errors:
                messages["error"].append(
                    gettext("Error in the %(field)s field - %(err)s",
                            field=getattr(form_add, field).label.text,
                            err=error))

    return messages, dep_name, list_unmet_deps, dep_message, new_input_id
コード例 #4
0
ファイル: utils_input.py プロジェクト: hwegge2/Mycodo
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)
コード例 #5
0
ファイル: utils_input.py プロジェクト: magichammer/Mycodo
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
コード例 #6
0
ファイル: utils_input.py プロジェクト: ciscomonkey/Mycodo
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