def page_live(): """ Page of recent and updating sensor data """ # Retrieve tables for the data displayed on the live page pid = PID.query.all() relay = Relay.query.all() sensor = Sensor.query.all() timer = Timer.query.all() # Display orders pid_display_order = csv_to_list_of_int(DisplayOrder.query.first().pid) sensor_display_order = csv_to_list_of_int( DisplayOrder.query.first().sensor) # Filter only activated sensors sensor_order_sorted = [] if sensor_display_order: for each_sensor_order in sensor_display_order: for each_sensor in sensor: if (each_sensor_order == each_sensor.id and each_sensor.is_activated): sensor_order_sorted.append(each_sensor.id) # Retrieve only parent method columns method = Method.query.all() return render_template('pages/live.html', measurement_units=MEASUREMENT_UNITS, method=method, pid=pid, relay=relay, sensor=sensor, timer=timer, pidDisplayOrder=pid_display_order, sensorDisplayOrderSorted=sensor_order_sorted)
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'))
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)
def lcd_del(lcd_id): action = u'{action} {controller}'.format(action=gettext(u"Delete"), controller=gettext(u"LCD")) error = [] lcd = LCD.query.filter(LCD.id == lcd_id).first() if lcd.is_activated: error.append( gettext(u"Deactivate LCD controller before modifying " u"its settings.")) if not error: try: # Delete all LCD Displays lcd_displays = LCDData.query.filter(LCDData.lcd_id == lcd_id).all() for each_lcd_display in lcd_displays: lcd_display_del(each_lcd_display.id, delete_last=True) # Delete LCD delete_entry_with_id(LCD, lcd_id) display_order = csv_to_list_of_int(DisplayOrder.query.first().lcd) display_order.remove(int(lcd_id)) DisplayOrder.query.first().lcd = list_to_csv(display_order) db.session.commit() except Exception as except_msg: error.append(except_msg) flash_success_errors(error, action, url_for('page_routes.page_lcd'))
def page_usage(): """ Display relay usage (duration and energy usage/cost) """ if not flaskutils.user_has_permission('view_stats'): return redirect(url_for('general_routes.home')) misc = Misc.query.first() relay = Relay.query.all() relay_stats = return_relay_usage(misc, relay) day = misc.relay_usage_dayofmonth if 4 <= day <= 20 or 24 <= day <= 30: date_suffix = 'th' else: date_suffix = ['st', 'nd', 'rd'][day % 10 - 1] display_order = csv_to_list_of_int(DisplayOrder.query.first().relay) return render_template('pages/usage.html', date_suffix=date_suffix, display_order=display_order, misc=misc, relay=relay, relay_stats=relay_stats, timestamp=time.strftime("%c"))
def math_del(form_mod_math): action = '{action} {controller}'.format(action=gettext("Delete"), controller=gettext("Math")) error = [] try: math = Math.query.filter(Math.id == form_mod_math.math_id.data).first() if math.is_activated: controller_activate_deactivate('deactivate', 'Math', form_mod_math.math_id.data) # Delete any conditionals associated with the controller conditionals = Conditional.query.filter( Conditional.math_id == form_mod_math.math_id.data).all() for each_cond in conditionals: conditional_actions = ConditionalActions.query.filter( ConditionalActions.conditional_id == each_cond.id).all() for each_cond_action in conditional_actions: db.session.delete(each_cond_action) db.session.delete(each_cond) db.session.commit() delete_entry_with_id(Math, form_mod_math.math_id.data) try: display_order = csv_to_list_of_int(DisplayOrder.query.first().math) display_order.remove(int(form_mod_math.math_id.data)) DisplayOrder.query.first().math = list_to_csv(display_order) except Exception: # id not in list pass db.session.commit() except Exception as except_msg: error.append(except_msg) flash_success_errors(error, action, url_for('routes_page.page_data'))
def input_del(form_mod): action = '{action} {controller}'.format(action=gettext("Delete"), controller=gettext("Input")) error = [] input_id = form_mod.input_id.data try: input_dev = Input.query.filter(Input.id == input_id).first() if input_dev.is_activated: input_deactivate_associated_controllers(input_id) controller_activate_deactivate('deactivate', 'Input', input_id) delete_entry_with_id(Input, input_id) try: display_order = csv_to_list_of_int( DisplayOrder.query.first().sensor) display_order.remove(int(input_id)) DisplayOrder.query.first().sensor = list_to_csv(display_order) except Exception: # id not in list pass db.session.commit() except Exception as except_msg: error.append(except_msg) flash_success_errors(error, action, url_for('routes_page.page_data'))
def page_pid(): """ Display PID settings """ pids = PID.query.all() relay = Relay.query.all() sensor = Sensor.query.all() display_order = csv_to_list_of_int(DisplayOrder.query.first().pid) form_add_pid = flaskforms.PIDAdd() form_mod_pid = flaskforms.PIDMod() method = Method.query.all() if request.method == 'POST': if not flaskutils.user_has_permission('edit_controllers'): return redirect(url_for('general_routes.home')) form_name = request.form['form-name'] if form_name == 'addPID': flaskutils.pid_add(form_add_pid) elif form_name == 'modPID': if form_mod_pid.delete.data: flaskutils.pid_del( form_mod_pid.pid_id.data) elif form_mod_pid.reorder_up.data: flaskutils.pid_reorder( form_mod_pid.pid_id.data, display_order, 'up') elif form_mod_pid.reorder_down.data: flaskutils.pid_reorder( form_mod_pid.pid_id.data, display_order, 'down') elif form_mod_pid.activate.data: flaskutils.pid_activate( form_mod_pid.pid_id.data) elif form_mod_pid.deactivate.data: flaskutils.pid_deactivate( form_mod_pid.pid_id.data) elif form_mod_pid.hold.data: flaskutils.pid_manipulate( form_mod_pid.pid_id.data, 'Hold') elif form_mod_pid.pause.data: flaskutils.pid_manipulate( form_mod_pid.pid_id.data, 'Pause') elif form_mod_pid.resume.data: flaskutils.pid_manipulate( form_mod_pid.pid_id.data, 'Resume') else: flaskutils.pid_mod(form_mod_pid) return redirect('/pid') return render_template('pages/pid.html', method=method, pids=pids, relay=relay, sensor=sensor, displayOrder=display_order, form_add_pid=form_add_pid, form_mod_pid=form_mod_pid)
def output_add(form_add): action = '{action} {controller}'.format(action=gettext("Add"), controller=gettext("Output")) error = [] unmet_deps = return_dependencies(form_add.relay_type.data) if unmet_deps: error.append( "The {dev} device you're trying to add has unmet dependencies: {dep}" .format(dev=form_add.relay_type.data, dep=unmet_deps)) if is_int(form_add.relay_quantity.data, check_range=[1, 20]): for _ in range(0, form_add.relay_quantity.data): try: new_relay = Output() new_relay.name = OUTPUT_INFO[form_add.relay_type.data]['name'] new_relay.relay_type = form_add.relay_type.data if form_add.relay_type.data == 'wired': new_relay.on_at_start = False elif form_add.relay_type.data == 'wireless_433MHz_pi_switch': new_relay.protocol = 1 new_relay.pulse_length = 189 new_relay.on_command = '22559' new_relay.off_command = '22558' elif form_add.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_type.data == 'command_pwm': new_relay.pwm_command = '/home/pi/script_pwm.sh ((duty_cycle))' elif form_add.relay_type.data == 'pwm': new_relay.pwm_hertz = 22000 new_relay.pwm_library = 'pigpio_any' if not error: 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')) if unmet_deps: return 1
def graph_del(form_del_graph): action = u'{action} {controller}'.format(action=gettext(u"Delete"), controller=gettext(u"Graph")) error = [] try: delete_entry_with_id(Graph, form_del_graph.graph_id.data) display_order = csv_to_list_of_int(DisplayOrder.query.first().graph) display_order.remove(int(form_del_graph.graph_id.data)) DisplayOrder.query.first().graph = list_to_csv(display_order) db.session.commit() except Exception as except_msg: error.append(except_msg) flash_success_errors(error, action, url_for('page_routes.page_graph'))
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)
def output_del(form_relay): action = '{action} {controller}'.format(action=gettext("Delete"), controller=gettext("Output")) error = [] try: delete_entry_with_id(Output, form_relay.relay_id.data) display_order = csv_to_list_of_int(DisplayOrder.query.first().relay) display_order.remove(int(form_relay.relay_id.data)) DisplayOrder.query.first().relay = list_to_csv(display_order) db.session.commit() manipulate_output('Delete', form_relay.relay_id.data) except Exception as except_msg: error.append(except_msg) flash_success_errors(error, action, url_for('routes_page.page_output'))
def dashboard_del(form_base): """Delete an item on the dashboard""" action = '{action} {controller}'.format(action=gettext("Delete"), controller=gettext("Dashboard")) error = [] try: delete_entry_with_id(Dashboard, form_base.dashboard_id.data) display_order = csv_to_list_of_int(DisplayOrder.query.first().graph) display_order.remove(int(form_base.dashboard_id.data)) DisplayOrder.query.first().graph = list_to_csv(display_order) db.session.commit() except Exception as except_msg: error.append(except_msg) flash_success_errors(error, action, url_for('routes_page.page_dashboard'))
def remote_host_del(form_setup): """Delete a remote Mycodo from the Remote Admin Dashboard""" if not utils_general.user_has_permission('edit_settings'): return redirect(url_for('general_routes.home')) try: delete_entry_with_id(Remote, form_setup.remote_id.data) display_order = csv_to_list_of_int( DisplayOrder.query.first().remote_host) display_order.remove(int(form_setup.remote_id.data)) DisplayOrder.query.first().remote_host = list_to_csv(display_order) db.session.commit() except Exception as except_msg: flash(gettext(u"Error: %(err)s", err=u'Remote Host Delete: {msg}'.format(msg=except_msg)), "error")
def timer_del(form_timer): action = '{action} {controller}'.format( action=gettext("Delete"), controller=gettext("Timer")) error = [] try: delete_entry_with_id(Timer, form_timer.timer_id.data) display_order = csv_to_list_of_int(DisplayOrder.query.first().timer) display_order.remove(int(form_timer.timer_id.data)) DisplayOrder.query.first().timer = list_to_csv(display_order) db.session.commit() except Exception as except_msg: error.append(except_msg) flash_success_errors(error, action, url_for('routes_page.page_timer'))
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_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) if unmet_deps: return 1
def page_lcd(): """ Display LCD output settings """ lcd = LCD.query.all() pid = PID.query.all() relay = Relay.query.all() sensor = Sensor.query.all() display_order = csv_to_list_of_int(DisplayOrder.query.first().lcd) form_add_lcd = flaskforms.LCDAdd() form_mod_lcd = flaskforms.LCDMod() if request.method == 'POST': if not flaskutils.user_has_permission('edit_controllers'): return redirect(url_for('general_routes.home')) if form_add_lcd.add.data: flaskutils.lcd_add(form_add_lcd.quantity.data) elif form_mod_lcd.save.data: flaskutils.lcd_mod(form_mod_lcd) elif form_mod_lcd.delete.data: flaskutils.lcd_del(form_mod_lcd.lcd_id.data) elif form_mod_lcd.reorder_up.data: flaskutils.lcd_reorder(form_mod_lcd.lcd_id.data, display_order, 'up') elif form_mod_lcd.reorder_down.data: flaskutils.lcd_reorder(form_mod_lcd.lcd_id.data, display_order, 'down') elif form_mod_lcd.activate.data: flaskutils.lcd_activate(form_mod_lcd.lcd_id.data) elif form_mod_lcd.deactivate.data: flaskutils.lcd_deactivate(form_mod_lcd.lcd_id.data) elif form_mod_lcd.reset_flashing.data: flaskutils.lcd_reset_flashing(form_mod_lcd.lcd_id.data) return redirect('/lcd') return render_template('pages/lcd.html', lcd=lcd, measurements=MEASUREMENTS, pid=pid, relay=relay, sensor=sensor, displayOrder=display_order, form_add_lcd=form_add_lcd, form_mod_lcd=form_mod_lcd)
def pid_del(pid_id): action = '{action} {controller}'.format(action=gettext("Delete"), controller=gettext("PID")) error = [] try: pid = PID.query.filter(PID.id == pid_id).first() if pid.is_activated: pid_deactivate(pid_id) delete_entry_with_id(PID, pid_id) display_order = csv_to_list_of_int(DisplayOrder.query.first().pid) display_order.remove(int(pid_id)) DisplayOrder.query.first().pid = list_to_csv(display_order) db.session.commit() except Exception as except_msg: error.append(except_msg) flash_success_errors(error, action, url_for('routes_page.page_function'))
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'))
def page_timer(): """ Display Timer settings """ timer = Timer.query.all() relay = Relay.query.all() relay_choices = flaskutils.choices_id_name(relay) display_order = csv_to_list_of_int(DisplayOrder.query.first().timer) form_timer = flaskforms.Timer() if request.method == 'POST': if not flaskutils.user_has_permission('edit_controllers'): return redirect(url_for('general_routes.home')) form_name = request.form['form-name'] if form_name == 'addTimer': flaskutils.timer_add(form_timer, request.form['timer_type'], display_order) elif form_name == 'modTimer': if form_timer.timerDel.data: flaskutils.timer_del(form_timer) elif form_timer.orderTimerUp.data: flaskutils.timer_reorder(form_timer.timer_id.data, display_order, 'up') elif form_timer.orderTimerDown.data: flaskutils.timer_reorder(form_timer.timer_id.data, display_order, 'down') elif form_timer.activate.data: flaskutils.timer_activate(form_timer) elif form_timer.deactivate.data: flaskutils.timer_deactivate(form_timer) elif form_timer.timerMod.data: flaskutils.timer_mod(form_timer) return redirect('/timer') return render_template('pages/timer.html', timer=timer, displayOrder=display_order, relay_choices=relay_choices, form_timer=form_timer)
def conditional_del(cond_id): """Delete a Conditional""" error = [] action = '{action} {controller}'.format( action=gettext("Mod"), controller=gettext("Conditional")) cond = Conditional.query.filter( Conditional.id == cond_id).first() # Deactivate conditional if active if cond.is_activated: conditional_deactivate(cond_id) try: if not error: # Delete conditional conditional_actions = ConditionalActions.query.filter( ConditionalActions.conditional_id == cond.id).all() for each_cond_action in conditional_actions: delete_entry_with_id(ConditionalActions, each_cond_action.id) delete_entry_with_id(Conditional, cond.id) try: display_order = csv_to_list_of_int(DisplayOrder.query.first().conditional) display_order.remove(int(cond.id)) DisplayOrder.query.first().conditional = list_to_csv(display_order) except Exception: # id not in list pass db.session.commit() except sqlalchemy.exc.OperationalError as except_msg: error.append(except_msg) except sqlalchemy.exc.IntegrityError as except_msg: error.append(except_msg) except Exception as except_msg: error.append(except_msg) flash_success_errors(error, action, url_for('routes_page.page_function'))
def method_delete(method_id): """Delete a method""" action = '{action} {controller}'.format(action=gettext("Delete"), controller=gettext("Method")) if not utils_general.user_has_permission('edit_settings'): return redirect(url_for('routes_method.method_list')) try: MethodData.query.filter( MethodData.method_id == int(method_id)).delete() Method.query.filter(Method.id == int(method_id)).delete() display_order = csv_to_list_of_int(DisplayOrder.query.first().method) display_order.remove(int(method_id)) DisplayOrder.query.first().method = list_to_csv(display_order) db.session.commit() flash("Success: {action}".format(action=action), "success") except Exception as except_msg: flash("Error: {action}: {err}".format(action=action, err=except_msg), "error") return redirect(url_for('routes_method.method_list'))
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)
def math_del(form_mod_math): action = u'{action} {controller}'.format(action=gettext(u"Delete"), controller=gettext(u"Math")) error = [] try: math = Math.query.filter(Math.id == form_mod_math.math_id.data).first() if math.is_activated: controller_activate_deactivate('deactivate', 'Math', form_mod_math.math_id.data) delete_entry_with_id(Math, form_mod_math.math_id.data) try: display_order = csv_to_list_of_int(DisplayOrder.query.first().math) display_order.remove(int(form_mod_math.math_id.data)) DisplayOrder.query.first().math = list_to_csv(display_order) except Exception: # id not in list pass db.session.commit() except Exception as except_msg: error.append(except_msg) flash_success_errors(error, action, url_for('page_routes.page_input'))
def sensor_del(form_mod_sensor): action = u'{action} {controller}'.format(action=gettext(u"Delete"), controller=gettext(u"Input")) error = [] try: sensor = Input.query.filter( Input.id == form_mod_sensor.modSensor_id.data).first() if sensor.is_activated: sensor_deactivate_associated_controllers( form_mod_sensor.modSensor_id.data) controller_activate_deactivate('deactivate', 'Input', form_mod_sensor.modSensor_id.data) conditionals = Conditional.query.filter( Conditional.sensor_id == form_mod_sensor.modSensor_id.data).all() for each_cond in conditionals: conditional_actions = ConditionalActions.query.filter( ConditionalActions.conditional_id == each_cond.id).all() for each_cond_action in conditional_actions: db.session.delete(each_cond_action) db.session.delete(each_cond) db.session.commit() delete_entry_with_id(Input, form_mod_sensor.modSensor_id.data) try: display_order = csv_to_list_of_int( DisplayOrder.query.first().sensor) display_order.remove(int(form_mod_sensor.modSensor_id.data)) DisplayOrder.query.first().sensor = list_to_csv(display_order) except Exception: # id not in list pass db.session.commit() except Exception as except_msg: error.append(except_msg) flash_success_errors(error, action, url_for('page_routes.page_input'))
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)
def lcd_add(quantity): action = u'{action} {controller}'.format(action=gettext(u"Add"), controller=gettext(u"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.id new_lcd_data.save() display_order = csv_to_list_of_int(DisplayOrder.query.first().lcd) DisplayOrder.query.first().lcd = add_display_order( display_order, new_lcd.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_lcd'))
def method_mod(form_mod_method): action = '{action} {controller}'.format( action=gettext("Modify"), controller=gettext("Method")) error = [] method = Method.query.filter( Method.id == form_mod_method.method_id.data).first() method_data = MethodData.query.filter( MethodData.id == form_mod_method.method_data_id.data).first() display_order = csv_to_list_of_int(method.method_order) try: if form_mod_method.Delete.data: delete_entry_with_id(MethodData, form_mod_method.method_data_id.data) if form_mod_method.method_select.data != 'relay': method_order = Method.query.filter(Method.id == method.id).first() display_order = csv_to_list_of_int(method_order.method_order) display_order.remove(method_data.id) method_order.method_order = list_to_csv(display_order) db.session.commit() return 0 if form_mod_method.rename.data: method.name = form_mod_method.name.data db.session.commit() return 0 # Ensure data is valid if validate_method_data(form_mod_method, method): return 1 if form_mod_method.method_select.data == 'setpoint': if method.method_type == 'Date': start_time = datetime.strptime(form_mod_method.time_start.data, '%Y-%m-%d %H:%M:%S') end_time = datetime.strptime(form_mod_method.time_end.data, '%Y-%m-%d %H:%M:%S') # Ensure the start time comes after the previous entry's end time # and the end time comes before the next entry's start time # method_id_set is the id given to all method entries, 'method_id', not 'id' previous_method = None next_method = None for index, each_order in enumerate(display_order): if each_order == method_data.id: if len(display_order) > 1 and index > 0: previous_method = MethodData.query.filter( MethodData.id == display_order[index-1]).first() if len(display_order) > index+1: next_method = MethodData.query.filter( MethodData.id == display_order[index+1]).first() if previous_method is not None and previous_method.time_end is not None: previous_end_time = datetime.strptime( previous_method.time_end, '%Y-%m-%d %H:%M:%S') if previous_end_time is not None and start_time < previous_end_time: error.append( gettext("The entry start time (%(st)s) cannot " "overlap the previous entry's end time " "(%(et)s)", st=start_time, et=previous_end_time)) if next_method is not None and next_method.time_start is not None: next_start_time = datetime.strptime( next_method.time_start, '%Y-%m-%d %H:%M:%S') if next_start_time is not None and end_time > next_start_time: error.append( gettext("The entry end time (%(et)s) cannot " "overlap the next entry's start time " "(%(st)s)", et=end_time, st=next_start_time)) method_data.time_start = start_time.strftime('%Y-%m-%d %H:%M:%S') method_data.time_end = end_time.strftime('%Y-%m-%d %H:%M:%S') elif method.method_type == 'Duration': if method_data.duration_sec == 0: method_data.duration_end = form_mod_method.duration_end.data else: method_data.duration_sec = form_mod_method.duration.data elif method.method_type == 'Daily': method_data.time_start = form_mod_method.daily_time_start.data method_data.time_end = form_mod_method.daily_time_end.data method_data.setpoint_start = form_mod_method.setpoint_start.data method_data.setpoint_end = form_mod_method.setpoint_end.data elif form_mod_method.method_select.data == 'relay': if method.method_type == 'Date': method_data.time_start = form_mod_method.relay_time.data elif method.method_type == 'Duration': method_data.duration_sec = form_mod_method.duration.data if form_mod_method.duration_sec.data == 0: method_data.duration_end = form_mod_method.duration_end.data if form_mod_method.relay_id.data == '': method_data.relay_id = None else: method_data.relay_id = form_mod_method.relay_id.data method_data.relay_state = form_mod_method.relay_state.data method_data.relay_duration = form_mod_method.relay_duration.data elif method.method_type == 'DailySine': if form_mod_method.method_select.data == 'relay': method_data.time_start = form_mod_method.relay_time.data if form_mod_method.relay_id.data == '': method_data.relay_id = None else: method_data.relay_id = form_mod_method.relay_id.data method_data.relay_state = form_mod_method.relay_state.data method_data.relay_duration = form_mod_method.relay_duration.data if not error: db.session.commit() except Exception as except_msg: error.append(except_msg) flash_success_errors(error, action, url_for('routes_method.method_list'))
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.id == form_add_method.method_id.data).first() display_order = csv_to_list_of_int(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_int(method.method_order) if display_order: last_method = MethodData.query.filter(MethodData.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 == 'relay': if method.method_type == 'Date': start_time = datetime.strptime(form_add_method.relay_time.data, '%Y-%m-%d %H:%M:%S') elif method.method_type == 'Daily': start_time = datetime.strptime(form_add_method.relay_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 == 'relay': add_method_data.time_start = form_add_method.relay_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 == 'relay': add_method_data.time_start = form_add_method.relay_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 == 'relay': add_method_data.relay_id = form_add_method.relay_id.data add_method_data.relay_state = form_add_method.relay_state.data add_method_data.relay_duration = form_add_method.relay_duration.data db.session.add(add_method_data) db.session.commit() # Add line to method data list if not a relay duration if form_add_method.method_select.data != 'relay': method.method_order = add_display_order(display_order, add_method_data.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 == 'relay': if method.method_type == 'Date': flash(gettext("Added relay modulation to method at start " "time: %(tm)s", tm=start_time), "success") elif method.method_type == 'Daily': flash(gettext("Added relay modulation to method at start " "time: %(tm)s", tm=start_time.strftime('%H:%M:%S')), "success") elif method.method_type == 'Duration': flash(gettext("Added relay 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'))
def input_add(form_add): action = '{action} {controller}'.format(action=gettext("Add"), controller=gettext("Input")) error = [] 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 new_sensor.multiplexer_bus = 1 else: new_sensor.i2c_bus = 0 new_sensor.multiplexer_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_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.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