Esempio n. 1
0
def index():
    if request.method == 'POST':
        _ovr = request.form['nm']

    global relay_status
    #titles = ["name", "actual_pwr","calcd_auto_sts", "ovr_sts"]
    titles = ["name", "switch-mode", "socket pwr", "auto control", "auto ovr"]
    table_rows = get_table_rows(relay_status, titles, "index")
    sun = get_sun()
    suntimes = (sun.getSunriseTimeLocal(), sun.getSunsetTimeLocal())
    return render_template('table.html',
                           table_rows=table_rows,
                           suntimes=suntimes,
                           config=relay_config,
                           titles=titles)
Esempio n. 2
0
def get_on_off_times(start_date, end_date, config, socket_name):
    # get a list of times and on/off transition
    transition_seq = []
    sr_ss_seq = []
    socket_cfg = config.sockets[socket_name]
    power = PowerStatus.PWR_UNK

    for d in daterange(start_date, end_date):
        sun = get_sun()
        sunset_lcl = sun.getSunsetTimeLocal(d)
        sunset_utc = sun.getSunsetTimeUtc(d)
        #sunrise_lcl = ConvertUtcToLocalTime(sunrise['dt'])
        sunrise_lcl = sun.getSunriseTimeLocal(d)
        sunrise_utc = sun.getSunriseTimeUtc(d)
        #sunset_lcl = ConvertUtcToLocalTime(sunset['dt'])
        sr_ss_seq.append((sunrise_lcl, sunset_lcl))

        # Calc the auto-values, ignoring override states
        socket_cfg.reset_state_activation_time()
        socket_cfg.calc_activate_times_for_states(d)
        record_for_today = False
        for state in socket_cfg.states:
            activation_time = state.activation_time.activation_time_lcl
            # if activation_time is None, then this state is not active
            if activation_time and state.active:
                record_for_today = True
                power = state.power_state
                transition_seq.append((activation_time, power))

        if record_for_today == False:
            # ie, no transistions occured today, then we need to create a record to mark
            # the current power at the start of the day
            marker_time = d.replace(hour=0, minute=0, second=0, microsecond=0)
            transition_seq.append((marker_time, power))

    transition_seq_ordered = []

    return transition_seq, sr_ss_seq
Esempio n. 3
0
def relay_process(control, config, status, overrides, socket_name=None):
    exit_code = relay_exit_codes.EXIT_CODE_OK
    try:
        global count
        count += 1
        # grab the semaphore to gaurd shared resource
        sem.acquire()
        # see if this is a simulated run and activate sim_time if true
        if control.simulate_run:
            activate_test_time(control.time)

        control.time = time_now()

        # fill in todays sunrise/sunset details
        sun = get_sun()
        #control.sunrise = sun.getSunriseTimeLocal(control.time)
        #control.sunset = sun.getSunsetTimeLocal(control.time)
        control.sunrise = sun.getSunriseTimeUtc(control.time)
        control.sunset = sun.getSunsetTimeUtc(control.time)
        #control.sunrise = AssignAsLocalTime(sunrise['dt'])
        #control.sunset = AssignAsLocalTime(sunset['dt'])

        # read the current board statuses
        if not control.simulate_run:
            retrieve_current_board_statuses(config)

        # process the overrides passed in.
        if overrides:
            process_overrides(config, status, overrides)

        # run on all sockets or just one?
        if socket_name != None:
            pass
            if socket_name not in config.sockets:
                return relay_exit_codes.EXIT_CODE_CMDLINE_ERROR_UNRECOGNISED_SOCKET
            if socket_name not in status.sockets:
                return relay_exit_codes.EXIT_CODE_CMDLINE_ERROR_UNRECOGNISED_SOCKET
            socket_cfg = config.sockets[socket_name]
            socket_sts = status.sockets[socket_name]
            # Calc the auto-values, ignoring override states
            socket_cfg.calc_status(socket_sts, control.time)
            # Send the next set of values to the boards, taking the overrides into account
            send_next_statuses(control, socket_cfg, socket_sts,
                               config.boards[socket_cfg.control_pwr.board])
        else:
            # iterate through all sockets
            for socket_name, socket_cfg in config.sockets.items():
                if socket_name not in status.sockets:
                    # create a socket-status instance....
                    new_skt_status = SocketStatus(socket_name, 0,
                                                  PowerStatus.PWR_OFF,
                                                  OverrideStatus.OVR_INACTIVE)
                    status.sockets[socket_name] = new_skt_status
                socket_sts = status.sockets[socket_name]
                # Calc the auto-values, ignoring override states
                socket_cfg.calc_status(socket_sts, control.time)
                send_next_statuses(control, socket_cfg, socket_sts,
                                   config.boards[socket_cfg.control_pwr.board])

        # re-write the status file
        if control.simulate_run:
            deactivate_test_time()
        else:
            #dir_path = os.path.dirname(os.path.realpath(__file__))
            #full_path = dir_path + '/' + ".relay-sts"
            #full_path = ".relay-sts"
            #status.write_file (full_path)
            status.write_file()

    except:
        exit_code = relay_exit_codes.EXIT_CODE_PROCESSING_RELAY_ERROR
        raise
    finally:
        pass
        sem.release()

    return exit_code
Esempio n. 4
0
def socket_info(socket_name):
    global relay_config
    global relay_func
    cfg_clone = relay_config.clone()
    #import cProfile
    #pr = cProfile.Profile()
    #pr.enable()

    time_now_utc = time_now()
    time_now_lcl = ConvertUtcToLocalTime(time_now_utc)
    time_now_lcl_str = time_now_lcl.strftime("%Y-%m-%d %H:%M:%S")
    fn_time_lcl_str = time_now_lcl.strftime("%Y%m")

    skt_mday_base = "{}_{}_{}".format(fn_time_lcl_str, socket_name,
                                      MULTI_DAY_MAP_FN)
    multi_day = os.path.join(web_svr.config['UPLOAD_FOLDER'], skt_mday_base)
    multi_day_fullbase = os.path.join(web_svr.root_path, 'static', multi_day)
    multi_day_full = os.path.join(web_svr.root_path, 'static',
                                  multi_day + ".png")

    board_name = cfg_clone.sockets[socket_name].control_pwr.board
    cfg_clone.add_board(
        Board(board_name, SimBoard.ModelName(), "/dev/ttyUsb0", 8))

    start_date = time_now_lcl - datetime.timedelta(days=100)
    end_date = time_now_lcl + datetime.timedelta(days=100)

    mday_base_file = Path(multi_day_full)
    if not mday_base_file.exists(
    ) or cfg_clone.sockets[socket_name].refresh_image():
        print_days_image(multi_day_full,
                         start_date,
                         end_date,
                         cfg_clone,
                         socket_name,
                         day_height=2)

    multi_day_full_ovrlay = multi_day_fullbase + "_overlay.png"
    multi_day = multi_day + "_overlay.png"
    overlay_current_day(multi_day_full,
                        multi_day_full_ovrlay,
                        start_date,
                        end_date,
                        cfg_clone,
                        socket_name,
                        time_now_lcl,
                        day_height=2)

    sts_clone = relay_status.clone()
    #titles = ["name", "actual_pwr","calcd_auto_sts", "ovr_sts"]
    titles = ["name", "switch-mode", "socket pwr", "auto control", "auto ovr"]
    socket_row = get_table_row(sts_clone, titles, socket_name, "socket_info")
    #pr.disable()
    #pr.print_stats()

    socket_links = get_sockets_in_line(cfg_clone)
    # reset info by cloning the real config again
    cfg_clone = relay_config.clone()
    sun = get_sun()
    suntimes = (sun.getSunriseTimeLocal(), sun.getSunsetTimeLocal())
    state_link = '<a href="http://{1}/socket_info/{0}/state">'.format(
        socket_name, websvr)

    return render_template('socket_info.html',
                           time_str=time_now_lcl_str,
                           table_row=socket_row,
                           socket_name=socket_name,
                           suntimes=suntimes,
                           config=relay_config,
                           titles=titles,
                           m_map=multi_day,
                           socket_links=socket_links,
                           state_link=state_link)
Esempio n. 5
0
    def convert_to_time(self, time_dict, timenow):
        sun = get_sun()

        basetime = time_dict["base"]
        modifier = time_dict["mod"]
        rand = time_dict["rand"]

        if basetime.strip() == ActivationTime.SUNSET_STR:
            sunset_lcl = sun.getSunsetTimeLocal(date=timenow)
            sunset_utc = sun.getSunsetTimeUtc(date=timenow)
            basetime_utc = sunset_utc

            hours = sunset_lcl.hour
            minutes = sunset_lcl.minute
            basetime_lcl = timenow.replace(hour=hours,
                                           minute=minutes,
                                           second=0,
                                           microsecond=0)

        elif basetime.strip() == ActivationTime.SUNRISE_STR:
            sunrise_lcl = sun.getSunriseTimeLocal(date=timenow)
            sunrise_utc = sun.getSunriseTimeUtc(date=timenow)
            basetime_utc = sunrise_utc

            hours = sunrise_lcl.hour
            minutes = sunrise_lcl.minute
            basetime_lcl = timenow.replace(hour=hours,
                                           minute=minutes,
                                           second=0,
                                           microsecond=0)

        else:
            (parse_ok, hours, mins) = ParseSimpleTime(basetime,
                                                      enforce_strict=True)
            if parse_ok:
                basetime_lcl = timenow.replace(hour=hours,
                                               minute=mins,
                                               second=0,
                                               microsecond=0)
                basetime_lcl = basetime_lcl.replace(tzinfo=None)
                basetime_lcl = AssignAsLocalTime(basetime_lcl)
                basetime_utc = ConvertLocalToUtcTime(basetime_lcl)

            else:
                return None
        isNegativeMod = False
        if modifier:
            isNegativeMod = modifier[0] == '-'
            if isNegativeMod:
                modifier = modifier[1:]

            (parse_ok, hours, mins) = ParseSimpleTime(modifier)
            if parse_ok:
                self.modifier = datetime.timedelta(0,
                                                   minutes=mins,
                                                   hours=hours)
            else:
                return None
        else:
            self.modifier = datetime.timedelta(0, 0, 0)

        isNegativeRand = False
        if rand:
            (parse_ok, hours, mins) = ParseSimpleTime(rand)
            if parse_ok:
                total_mins = (60 * hours) + mins
                rmins = random.randint(-total_mins, total_mins)
                if rmins < 0:
                    isNegativeRand = True
                    rmins = -rmins
                rand = datetime.timedelta(0, minutes=rmins)
            else:
                return None
        else:
            rand = datetime.timedelta(0, 0, 0)

        time_utc = 0
        if isNegativeMod:
            time_utc = basetime_utc - self.modifier
        else:
            time_utc = basetime_utc + self.modifier

        if isNegativeRand:
            time_utc -= rand
        else:
            time_utc += rand

        return time_utc