def function_add(form_add_func): messages = {"success": [], "info": [], "warning": [], "error": []} new_function_id = None dep_name = None 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]) messages["error"].append( "{dev} has unmet dependencies. They must be installed before the Function can be added." .format(dev=function_name)) if function_name in dict_controllers: dep_name = dict_controllers[function_name]['function_name'] else: messages["error"].append( "Function not found: {}".format(function_name)) return messages, dep_name, list_unmet_deps, None new_func = None try: if function_name == 'conditional_conditional': new_func = Conditional() new_func.position_y = 999 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") if not hasattr(self, "loop_count"): # Initialize objects saved across executions self.loop_count = 1 else: self.loop_count += 1 # 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''' new_func.conditional_status = ''' # Example code to provide a return status for other controllers and widgets. status_dict = { 'string_status': "This is the demo status of the conditional controller. " "The controller has looped {} times".format(self.loop_count), 'loop_count': self.loop_count, 'error': [] } return status_dict''' if not messages["error"]: new_func.save() new_function_id = new_func.unique_id if not current_app.config['TESTING']: save_conditional_code(messages["error"], new_func.conditional_statement, new_func.conditional_status, new_func.unique_id, ConditionalConditions.query.all(), Actions.query.all(), test=False) elif function_name == 'pid_pid': new_func = PID() new_func.position_y = 999 new_func.save() new_function_id = new_func.unique_id 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 messages["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_run_pwm_method', 'trigger_sunrise_sunset' ]: new_func = Trigger() new_func.name = '{}'.format(FUNCTION_INFO[function_name]['name']) new_func.trigger_type = function_name new_func.position_y = 999 if not messages["error"]: new_func.save() new_function_id = new_func.unique_id elif function_name == 'function_actions': new_func = Function() new_func.position_y = 999 new_func.function_type = function_name if not messages["error"]: new_func.save() new_function_id = new_func.unique_id elif function_name in dict_controllers: # Custom Function Controller new_func = CustomController() new_func.device = function_name new_func.position_y = 999 if 'function_name' in dict_controllers[function_name]: new_func.name = dict_controllers[function_name][ 'function_name'] else: new_func.name = 'Function Name' # Generate string to save from custom options messages["error"], custom_options = custom_options_return_json( messages["error"], dict_controllers, device=function_name, use_defaults=True) new_func.custom_options = custom_options new_func.unique_id = set_uuid() if ('execute_at_creation' in dict_controllers[new_func.device] and not current_app.config['TESTING']): messages["error"], new_func = dict_controllers[ new_func.device]['execute_at_creation']( messages["error"], new_func, dict_controllers[new_func.device]) if not messages["error"]: new_func.save() new_function_id = new_func.unique_id elif function_name == '': messages["error"].append("Must select a function type") else: messages["error"].append( "Unknown function type: '{}'".format(function_name)) if not messages["error"]: if function_name in dict_controllers: # # Add measurements defined in the Function Module # if ('measurements_dict' in dict_controllers[function_name] and dict_controllers[function_name]['measurements_dict']): for each_channel in dict_controllers[function_name][ 'measurements_dict']: measure_info = dict_controllers[function_name][ 'measurements_dict'][each_channel] new_measurement = DeviceMeasurements() new_measurement.device_id = new_func.unique_id if 'name' in measure_info: new_measurement.name = measure_info['name'] else: new_measurement.name = "" if 'measurement' in measure_info: new_measurement.measurement = measure_info[ 'measurement'] else: new_measurement.measurement = "" if 'unit' in measure_info: new_measurement.unit = measure_info['unit'] else: new_measurement.unit = "" new_measurement.channel = each_channel new_measurement.save() # # If there are a variable number of measurements # elif ('measurements_variable_amount' in dict_controllers[function_name] and dict_controllers[function_name] ['measurements_variable_amount']): # Add first default measurement with empty unit and measurement new_measurement = DeviceMeasurements() new_measurement.name = "" new_measurement.device_id = new_func.unique_id new_measurement.measurement = "" new_measurement.unit = "" new_measurement.channel = 0 new_measurement.save() # # Add channels defined in the Function Module # if 'channels_dict' in dict_controllers[function_name]: for each_channel, channel_info in dict_controllers[ function_name]['channels_dict'].items(): new_channel = FunctionChannel() new_channel.channel = each_channel new_channel.function_id = new_func.unique_id # Generate string to save from custom options messages[ "error"], custom_options = custom_channel_options_return_json( messages["error"], dict_controllers, None, new_func.unique_id, each_channel, device=new_func.device, use_defaults=True) new_channel.custom_options = custom_options new_channel.save() messages["success"].append('{action} {controller}'.format( action=TRANSLATIONS['add']['title'], controller=TRANSLATIONS['function']['title'])) except sqlalchemy.exc.OperationalError as except_msg: messages["error"].append(str(except_msg)) except sqlalchemy.exc.IntegrityError as except_msg: messages["error"].append(str(except_msg)) except Exception as except_msg: logger.exception("Add Function") messages["error"].append(str(except_msg)) return messages, dep_name, dep_unmet, new_function_id
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_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' # Generate string to save from custom options error, custom_options = custom_options_return_json( error, dict_controllers, device=function_name, use_defaults=True) new_func.custom_options = custom_options new_func.unique_id = set_uuid() if ('execute_at_creation' in dict_controllers[new_func.device] and not current_app.config['TESTING']): error, new_func = dict_controllers[ new_func.device]['execute_at_creation']( error, new_func, dict_controllers[new_func.device]) 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() if function_name in dict_controllers: # # Add measurements defined in the Function Module # if ('measurements_dict' in dict_controllers[function_name] and dict_controllers[function_name]['measurements_dict']): for each_channel in dict_controllers[function_name][ 'measurements_dict']: measure_info = dict_controllers[function_name][ 'measurements_dict'][each_channel] new_measurement = DeviceMeasurements() new_measurement.device_id = new_func.unique_id if 'name' in measure_info: new_measurement.name = measure_info['name'] else: new_measurement.name = "" if 'measurement' in measure_info: new_measurement.measurement = measure_info[ 'measurement'] else: new_measurement.measurement = "" if 'unit' in measure_info: new_measurement.unit = measure_info['unit'] else: new_measurement.unit = "" new_measurement.channel = each_channel new_measurement.save() # # If there are a variable number of measurements # elif ('measurements_variable_amount' in dict_controllers[function_name] and dict_controllers[function_name] ['measurements_variable_amount']): # Add first default measurement with empty unit and measurement new_measurement = DeviceMeasurements() new_measurement.name = "" new_measurement.device_id = new_func.unique_id new_measurement.measurement = "" new_measurement.unit = "" new_measurement.channel = 0 new_measurement.save() # # Add channels defined in the Function Module # if 'channels_dict' in dict_controllers[function_name]: for each_channel, channel_info in dict_controllers[ function_name]['channels_dict'].items(): new_channel = FunctionChannel() new_channel.channel = each_channel new_channel.function_id = new_func.unique_id # Generate string to save from custom options error, custom_options = custom_channel_options_return_json( error, dict_controllers, None, new_func.unique_id, each_channel, device=new_func.device, use_defaults=True) new_channel.custom_options = custom_options new_channel.save() 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: logger.exception("Add Function") error.append(except_msg) flash_success_errors(error, action, url_for('routes_page.page_function')) if dep_unmet: return 1
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_controller_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.startswith('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.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 if not error: new_measurement.save() elif function_name.startswith('trigger_'): 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.startswith('function_'): 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: new_func = CustomController() new_func.device = function_name if 'controller_name' in dict_controllers[function_name]: new_func.name = dict_controllers[function_name][ 'controller_name'] else: new_func.name = 'Controller Name' list_options = [] if 'custom_options' in dict_controllers[function_name]: for each_option in dict_controllers[function_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_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
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'))