Exemplo n.º 1
0
def cancel_rule():
    """User can remove rule from ongoing rules table."""
    content = request.json["list"]

    for rule_id in content:
        # select l.interval_id, li.name from life as l, lines as li where id = {0} and l.line_id = li.number
        res = database.select(database.QUERY[mn() + "_1"].format(rule_id),
                              "fetchone")
        if res is None:
            logging.error(
                "No {0} rule/interval id in database".format(rule_id))
            abort(500)

        interval_id = res[0]
        ongoing_rule_id = res[2]
        # branch_name = res[1]
        # "UPDATE life SET state=4 WHERE interval_id = '{0}' and state = 1 and rule_id = 1"
        database.update(database.QUERY[mn() + "_2"].format(interval_id))

        res = database.select(
            database.QUERY[mn() +
                           "_select_ongoing_rule"].format(ongoing_rule_id),
            "fetchone",
        )
        if res is None:
            logging.info("No intervals for {0} ongoing rule. Remove it".format(
                ongoing_rule_id))
            database.update(
                database.QUERY[mn() +
                               "_delete_ongoing_rule"].format(ongoing_rule_id))

        logging.info("Rule '{0}' canceled".format(rule_id))

    update_all_rules()

    try:
        lines = {}
        for line_id, line in BRANCHES_SETTINGS.items():
            response_status = remote_controller.line_status(line_id=line_id)
            lines[line_id] = dict(id=line_id,
                                  state=int(response_status[line_id]["state"]))

        arr = form_responce_for_branches(lines)
        send_branch_status_message(arr)
    except Exception as e:
        logging.error(e)
        logging.error("Can't get Raspberri Pi pin status. Exception occured")
        abort(500)

    send_history_change_message()
    return json.dumps({"status": "OK"})
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],
                "is_except": row[3],
                "group_id": row[4],
                "line_name": row[5],
                "group_name": row[6],
                "base_url": row[7],
                "device_id": row[8],
                "device_url": row[9],
                "pump_enabled": row[10],
                "pump_pin": 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))
Exemplo n.º 3
0
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)
Exemplo n.º 4
0
def setup_lines_datalogger():
    try:
        lines = database.select(database.QUERY[mn()])
        for row in lines:
            key = row[0]

            LINES[key] = {"id": row[0], "moisture_id": row[1]}

        logging.info(LINES)
    except Exception as e:
        logging.error(
            "Exceprion occured when trying to get settings for all branches. {0}".format(
                e
            )
        )
Exemplo n.º 5
0
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], "base_url": row[2]}

        logging.info(SENSORS)
    except Exception as e:
        logging.error(
            "Exceprion occured when trying to get settings for all sensors. {0}".format(
                e
            )
        )
Exemplo n.º 6
0
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)
Exemplo n.º 7
0
def get_settings():
    """Fill up settings array to save settings for branches."""
    try:
        branches = database.select(database.QUERY[mn()])
        for row in branches:
            branch_id = row[0]
            name = row[1]
            time = row[2]
            intervals = row[3]
            time_wait = row[4]
            start_time = row[5]
            line_type = row[6]
            base_url = row[7]
            pump_enabled = row[8]
            is_pump = row[9]
            group_id = row[10]
            group_name = row[11]
            relay_num = row[12]

            BRANCHES_SETTINGS[branch_id] = {
                "branch_id": branch_id,
                "name": name,
                "time": time,
                "intervals": intervals,
                "time_wait": time_wait,
                "start_time": start_time,
                "line_type": line_type,
                "base_url": base_url,
                "pump_enabled": True if pump_enabled == 1 else False,
                "is_pump": is_pump,
                "group_id": group_id,
                "group_name": group_name,
                "relay_num": relay_num,
            }

            logging.debug("{0} added to settings".format(
                str(BRANCHES_SETTINGS[branch_id])))

        global APP_SETTINGS
        APP_SETTINGS = database.get_app_settings()
        logging.info("APP settings: {0}".format(str(APP_SETTINGS)))

    except Exception as e:
        logging.error(
            "Exceprion occured when trying to get settings for all branches. {0}"
            .format(e))
Exemplo n.º 8
0
def get_moisture():
    try:
        list_arr = database.select(database.QUERY[mn()], "fetchall")
        if list_arr is not None:
            list_arr.sort(key=itemgetter(0))

            grouped = {}
            for key, group in groupby(list_arr, itemgetter(0)):
                _list = list()
                for thing in group:
                    _list.append([
                        round(thing[1], 2),
                        int(convert_to_datetime(thing[2]).strftime("%H")),
                    ])
                grouped[key] = {}
                grouped[key]["new"] = _list

            for key, value in grouped.items():
                new_list = list()
                for _key, _group in groupby(value["new"], itemgetter(1)):
                    _sum = 0
                    _len = 0
                    for thing in _group:
                        _sum += thing[0]
                        _len += 1
                    new_list.append(dict(hours=_key, val=round(_sum / _len,
                                                               2)))
                grouped[key]["new"] = new_list
                grouped[key]["base"] = 60

            for key, value in grouped.items():
                del value["new"][::2]

    except Exception as e:
        raise e
    return jsonify(data=grouped)
Exemplo n.º 9
0
def migrate_data():
    database.select(database.QUERY[mn()])

    database.update(database.QUERY[mn() + "_insert"])
Exemplo n.º 10
0
def activate_branch():
    """Blablbal."""
    # ============ check input params =======================
    mode = request.args.get("mode")
    if mode is None:
        logging.error("no 'mode' parameter passed")
        abort(500)

    if mode == "single":
        branch_id = int(request.args.get("id"))
        time_min = int(request.args.get("time_min"))
    elif mode == "interval":
        branch_id = int(request.args.get("id"))
        time_min = int(request.args.get("time_min"))
        time_wait = int(request.args.get("time_wait"))
        num_of_intervals = int(request.args.get("quantity"))
    elif mode == "auto":
        branch_id = int(request.args.get("id"))
        time_min = int(request.args.get("time_min"))
    else:
        logging.error("incorrect mode parameter passed: {0}".format(mode))
        abort(500)
    # ============ check input params =======================

    response_arr = get_line_status(branch_id)
    if response_arr[branch_id]["state"] != 1:
        try:
            response_arr = retry_branch_on(branch_id=branch_id,
                                           time_min=time_min)
        except Exception as e:
            logging.error(e)
            logging.error(
                "Can't turn on branch id={0}. Exception occured".format(
                    branch_id))
            abort(500)

        # needs to be executed in both cases single and interval, but in in auto
        if mode != "auto":
            interval_id = str(uuid.uuid4())
            now = datetime.datetime.now()
            stop_time = now + datetime.timedelta(minutes=time_min)

            database.update(database.QUERY[mn() + "_1"].format(
                branch_id, 1, 2, now.date(), now, interval_id, time_min))
            lastid = database.update(database.QUERY[mn() + "_1"].format(
                branch_id, 2, 1, now.date(), stop_time, interval_id, 0))
            logging.debug("lastid:{0}".format(lastid))

            res = database.select(database.QUERY[mn() + "_2"].format(lastid),
                                  "fetchone")
            logging.debug("res:{0}".format(res[0]))

            set_next_rule_to_redis(
                branch_id,
                {
                    "id": res[0],
                    "line_id": res[1],
                    "rule_id": res[2],
                    "user_friendly_name": res[6],
                    "timer": res[3],
                    "interval_id": res[4],
                    "time": res[5],
                },
            )
            logging.info("Rule '{0}' added".format(
                str(database.get_next_active_rule(branch_id))))

        if mode == "interval":
            # first interval is already added
            for x in range(2, num_of_intervals + 1):
                start_time = stop_time + datetime.timedelta(minutes=time_wait)
                stop_time = start_time + datetime.timedelta(minutes=time_min)
                database.update(database.QUERY[mn() + "_1"].format(
                    branch_id, 1, 1, now.date(), start_time, interval_id,
                    time_min))
                database.update(database.QUERY[mn() + "_1"].format(
                    branch_id, 2, 1, now.date(), stop_time, interval_id, 0))
                logging.info(
                    "Start time: {0}. Stop time: {1} added to database".format(
                        str(start_time), str(stop_time)))

        if mode == "auto":
            logging.info(
                "Branch '{0}' activated from rules service".format(branch_id))
        else:
            logging.info("Branch '{0}' activated manually".format(branch_id))
    else:
        logging.info(
            "Branch '{0}' already activated no action performed".format(
                branch_id))

    arr = form_responce_for_branches(response_arr)
    send_branch_status_message(arr)
    send_history_change_message()

    return jsonify(branches=arr)