def setup_sensors_datalogger(): try: lines = database.select(database.QUERY[mn()]) logging.info(database.QUERY[mn()]) for row in lines: key = row[0] SENSORS[key] = {"id": row[0], "type": row[1]} logging.info(SENSORS) except Exception as e: logging.error( "Exceprion occured when trying to get settings for all sensors. {0}" .format(e))
def setup_lines_remote_control(): """Fill up settings array to save settings for branches.""" try: lines = database.select(database.QUERY[mn()]) for row in lines: key = row[0] if row[7] is None and row[9] is None: continue LINES[key] = { "id": row[0], "relay_num": row[1], "is_pump": row[2], "group_id": row[3], "line_name": row[4], "group_name": row[5], "base_url": row[6], "linked_device_id": row[7], "linked_device_url": row[8], "pump_enabled": row[9], "pump_pin": row[10], "device_id": row[11], "state": -1, } logging.info(LINES) except Exception as e: logging.error( "Exceprion occured when trying to get settings for all branches. {0}" .format(e))
def history(): """Return history page if no parameters passed and only table body if opposite.""" if "days" in request.args: days = int(request.args.get("days")) else: days = 7 # SELECT l.interval_id, li.name, l.date, l.timer as \"[timestamp]\", l.active, l.time grouped_rules = OrderedDict() list_arr = database.select(database.QUERY[mn()].format(days), "fetchall") if list_arr is not None: list_arr.sort(key=itemgetter(0)) grouped = [] for key, group in groupby(list_arr, itemgetter(0)): grouped.append(list([list(thing) for thing in group])) rules = [] for intervals in grouped: intervals.sort(key=itemgetter(3)) intervals_quantity = len(intervals) time_wait = 0 if intervals_quantity == 2: time_wait = int( (intervals[1][3] - intervals[0][3]).total_seconds() / 60 - intervals[0][5] ) row = intervals[0] rules.append( dict( line_name=row[1], date=row[2].strftime("%m/%d/%Y"), date_description=form_date_description(row[2]), timer=date_handler(row[3]), ative=row[4], time=row[5], intervals=intervals_quantity, interval_id=row[0], time_wait=time_wait, ) ) rules.sort(key=itemgetter("date")) for key, group in groupby(rules, itemgetter("date")): grouped_rules[key] = [thing for thing in group] for key, value in grouped_rules.items(): value.sort(key=itemgetter("timer")) return render_template("history.html", my_list=grouped_rules)
def ongoing_rules(): """Return ongoing_rules.html.""" list_arr = database.select(database.QUERY[mn()], "fetchall") if list_arr is None: list_arr = [] rows = [] now = datetime.datetime.now() # SELECT id, line_id, time, intervals, time_wait, repeat_value, dow, date_start, time_start, end_value, end_date, end_repeat_quantity for row in list_arr: rule_id = row[10] line_id = row[1] time = row[2] intervals = row[3] time_wait = row[4] repeat_value = row[5] date_time_start = row[6] end_date = row[7] active = row[8] name = row[9] days = -1 start_dt = convert_to_datetime(date_time_start) end_dt = convert_to_datetime(end_date) if start_dt.date() == end_dt.date(): date_delta = end_dt.date() - now.date() if date_delta.days == 0: days = 0 if date_delta.days == 1: days = 1 rows.append( { "rule_id": rule_id, "line_id": line_id, "time": time, "intervals": intervals, "time_wait": time_wait, "repeat_value": repeat_value, "date_time_start": str(date_time_start), "end_date": str(end_date), "active": active, "line_name": name, "days": days, } ) return render_template("ongoing_rules.html", my_list=rows)
def enable_rule(): """Synch with redis each 10 seconds. Execute rules if any.""" try: logging.info("enable rule thread started.") logging.info("Updating rules on start.") update_all_rules() logging.info("Synch with redis.") sync_rules_from_redis() rules_to_log() logging.info("Entering While loop") start_time = datetime.datetime.now() while True: # logging.info("enable_rule_daemon heartbeat. RULES_FOR_BRANCHES: {0}".format(str(RULES_FOR_BRANCHES))) time.sleep(10) sync_rules_from_redis() for rule in config.RULES_FOR_BRANCHES: if rule is None: continue now_time = datetime.datetime.now() # Send message to log ones per 10 minutes delta = now_time - start_time if delta.seconds >= 60 * 10: rules_to_log() start_time = now_time # send message to messenger X minutes before rules execution started if now_time >= ( rule["timer"] - datetime.timedelta(minutes=config.MESSENGER_SENT_TIMEOUT) ): try: send_to_viber_bot(rule) except Exception as e: logging.error( "Can't send rule {0} to viber. Exception occured. {1}".format( str(rule), e ) ) # Start of execution if now_time >= rule["timer"]: # Check rain volume for last X hours if inspect_conditions(rule) is False: logging.error( "Rule can't be executed cause of rain volume too high" ) database.update( database.QUERY[mn() + "_canceled_by_rain"].format( rule["id"] ) ) set_next_rule_to_redis( rule["line_id"], database.get_next_active_rule(rule["line_id"]), ) continue # Troubleshoot case. In case timedelta more than 5 minutes - skip rule logging.info( "Rule '{0}' execution is about to start. Checking time delta not more than '{1}' minutes".format( str(rule), config.MAX_TIME_DELTA_FOR_RULES_SERVICE_MIN ) ) delta = now_time - rule["timer"] if delta.seconds >= 60 * config.MAX_TIME_DELTA_FOR_RULES_SERVICE_MIN: logging.error( "Rule execution won't be started since time delta more than'{0}' minutes".format( config.MAX_TIME_DELTA_FOR_RULES_SERVICE_MIN ) ) database.update( database.QUERY[mn() + "_canceled_by_mistime"].format( rule["id"] ) ) set_next_rule_to_redis( rule["line_id"], database.get_next_active_rule(rule["line_id"]), ) continue else: logging.info("Rule execution allowed") logging.info("Rule '{0}' execution started".format(str(rule))) try: if rule["rule_id"] == 1: branch_on(rule["line_id"], rule["time"]) if rule["rule_id"] == 2: branch_off(rule["line_id"]) except Exception as e: logging.error( "Rule '{0}' can't be executed. Exception occured. {1}".format( str(rule), e ) ) # Set failed state database.update( database.QUERY[mn() + "_cancel_interval"].format( rule["interval_id"], 3 ) ) database.update(database.QUERY[mn()].format(rule["id"], 3)) else: logging.info("Rule '{0}' is done.".format(str(rule))) # Set ok state database.update(database.QUERY[mn()].format(rule["id"], 2)) finally: logging.info( "Get next active rule for {0} line id.".format( rule["line_id"] ) ) set_next_rule_to_redis( rule["line_id"], database.get_next_active_rule(rule["line_id"]), ) except Exception as e: logging.error("enable rule thread exception occured. {0}".format(e)) finally: logging.info("enable rule thread stopped.")