def set_folder(self, tries=3, check_access=True): """Set folder to trassir settings Args: tries (int, optional): Numbers of tris to set folder. Default 3. check_access (bool, optional): Check write access if True. Default True. """ host.stats()["run_count"] = tries try: new_folder = self.folder.mount() if check_access: self._check_path(new_folder) host.stats()["run_count"] = 0 except Exception as err: # pylint: disable=W0703 if tries: logger.warning("%s attempt failed with error: %s", tries, err) host.timeout( 1000, lambda: self.set_folder( tries=(tries - 1), check_access=check_access ), ) else: logger.error("%s attempt failed with error: %s", tries, err) raise_from_thread(err) return self._set_screenshots_folder(new_folder) if self.folder.rollback is True: host.register_finalizer(self.rollback)
def remover(self): if not self.paths_to_check: self._working = False return self._working = True if time.time() - self.create_last_time < self.delay_to_del: # Если псоледнее создание файла произошло неадвно host.timeout(120000, self.remover) return for path in self.paths_to_check: if not os.path.exists(path): continue if not os.path.isdir(path): path = os.path.dirname(path) tree_iter = os.walk(path) try: tree_info = next(tree_iter) except StopIteration: continue for folder in tree_info[1]: print(folder) to_del_path = os.path.join(path, folder) try: shutil.rmtree(os.path.join(to_del_path)) except OSError: logger.exception("Can't delete folder: %s", to_del_path) for _file in tree_info[2]: to_del_path = os.path.join(path, _file) try: os.remove(to_del_path) except OSError: logger.exception("Can't delete file: %s", to_del_path) host.timeout(120000, self.remover)
def show_timer(self): """Loop runner. Deletes channels which time to show expired""" count = 0 now = int(time.time()) try: channel, event_info = next(self._displaying_channels.iteritems()) except StopIteration: logger.debug( "no data in _displaying_channels, show timer stopping") self.show_timer_running = False return self.show_timer_running = True if event_info.get("start_to_show", 0) and (now - event_info.get("start_to_show", 0) > self.show_channel_duration): logger.debug("deleting expired channel: %s", channel) count += 1 try: del self._displaying_channels[channel] except KeyError: logger.debug("can't delete _displaying_channels[%s]", channel) if not self._displaying_channels: self.show_timer_running = False self._show_channels_on_display() return if count: self._show_channels_on_display() if not event_info.get("start_to_show", 0): self._show_channels_on_display() host.timeout(1000, self.show_timer)
def carousel_go(self): if not self.hand_using: if self.idx >= len(self.carousel_dict): self.idx = 0 getattr(self, self.func)() self.idx += 1 host.timeout(1000 * TIMEOUT, self.carousel_go)
def write_test(): try: with open(test_file, "w") as f: f.write("hello from trassir") raise ValueError(test_file) except Exception as err: host.timeout(1, lambda: raise_from_thread(err))
def show_timer(self): """Loop runner. Deletes channels which time to show expired""" self.show_timer_running = True count = 0 now = int(time.time()) for channel, event_info in self._displaying_channels.items(): if event_info.get("start_to_show", 0) and (now - event_info.get("start_to_show", 0) > self.show_channel_duration): if self.no_motion_check and host.object(channel).state( "motion"): logger.debug("Motion detected on channel (%s), skip it", channel) continue logger.debug("deleting expired channel: %s", channel) try: del self._displaying_channels[channel] count += 1 except KeyError: logger.debug("can't delete _displaying_channels[%s]", channel) if not self._displaying_channels: self.show_timer_running = False self._show_channels_on_display() return if count: self._show_channels_on_display() host.timeout(1000, self.show_timer)
def get(self, request, *args, **kwargs): request_dict = request.GET dt = None channel_full_guid = "{}_{}".format( request_dict["channel_guid"], request_dict["server_guid"] ) if request_dict.get("dt") != None: dt = datetime.strptime(request_dict["dt"], "%Y%m%d_%H%M%S") figures = request_dict.get("figures") file_name = request_dict.get("file_name") file_path = request_dict.get("file_path") try: task_guid, shot_path = ss.save( channel_full_guid, dt, figures, file_name, file_path ) check_work_state[task_guid] = None logger.debug("New task: <b>%s</b><br>File: %s" % (task_guid, shot_path)) except (ValueError, EnvironmentError) as err: host.error(str(err)) return HttpResponse(str(err)) while check_work_state[task_guid] not in (status.success, status.error): time.sleep(0.1) state = check_work_state.pop(task_guid) if state == status.success: logger.debug("status.success") host.timeout(1000, lambda: self.delete_file(shot_path)) with open(r"{}".format(shot_path), "rb") as img: response = HttpResponse(img.read()) response.headers["Content-Type"] = "image/jpeg" # response.headers["Content-Disposition"] = "attachment; filename='%s'" % os.path.basename(shot_path) return response else: return HttpResponse("Can't get shot")
def _work_iteration(self): changed = self.__day_changed if changed: self.remove_shots() if self.working: host.timeout(1000 * self.SLEEP_TIMEOUT_SEC, self._work_iteration)
def draw_figures(): for guid in get_channels(CHANNELS): draw( guid, text_ext(X1, Y1, X2, Y2, CUSTOM_STRING, BACKGROUND_COLOR, FONT_COLOR, FONT_SIZE), ) host.timeout(30000, draw_figures)
def start(): res = commands.getoutput( "cat /sys/class/thermal/thermal_zone0/temp | cut -c 1-2") dt_str = datetime.now().strftime("%d.%m.%Y %H:%M:%S") # raise ValueError(res) log.write(res + "°C") host.stats()["run_count"] += 1 host.timeout(1000 * DELAY, start)
def show_chans(self): self.gui.show_template(ALARM_TEMPLATE, ATTENTION_MONITOR) try: self.gui.show("gui7(-1, '')", ATTENTION_MONITOR) self.gui.assign_channels(",".join(self.chan_on_template), ATTENTION_MONITOR) except Exception as e: host.alert("ERROR: %s" % e) host.timeout(1000 * ATTENTION_TIMEOUT, self.del_old)
def patrol(self): if self.__current_work_mode == "patrol": if time.time() - self.__last_ad_activity_ts > self.ad_timeout: self.set_preset(self.patrol_path) timeout = self.get_timeout() logger.debug("Go next preset after %s", timeout) host.timeout(timeout * 1000, self.patrol) else: host.timeout(1000, self.patrol)
def _timer(self): if self.ts_to_come_back < time.time(): logger.debug( "Timer is stopping. %s < %s", self.ts_to_come_back, time.time() ) self.open_flag = False self.last_method() self.ts_to_come_back = 0 else: host.timeout(1000, self._timer)
def loop(): free_disk_space = int(psutil.disk_usage(clean_folder).free) if MIN_FREE_SPACE == 0: folder_checker(clean_folder, FILE_AGE, ext_list, free_disk_space, MIN_FREE_SPACE) host.timeout(CHECK_INTERVAL * 60000, loop) else: if free_disk_space < MIN_FREE_SPACE * 1024 * 1024: folder_checker(clean_folder, FILE_AGE, ext_list, free_disk_space, MIN_FREE_SPACE) host.timeout(CHECK_INTERVAL * 60000, loop)
def __events_checker(self): if not self.__current_events: self.__working_now = False return ts_now = time.time() for guid in self.__current_events.keys(): if ts_now > self.__current_events[guid].callback_ts: self.__callback(self.__current_events.pop(guid)) host.timeout(self.duration * 100, self.__events_checker)
def old_events_cleaner(self): if not self.events: self.working = False return self.working = True for channel, persons_info in self.events.items(): for person, recognize_ts in persons_info.items(): if time.time() - recognize_ts > self.store_time: logger.debug("Deleting info about person: %s", person) del persons_info[person] if not self.events[channel]: logger.debug("deleting info about channel: %s", channel) del self.events[channel] host.timeout(20000, self.old_events_cleaner)
def show_chans(self): logger.debug("go to show %s" % self.chan_on_template) if len(self.chan_on_template) > 9: self.del_old() return try: self.operate_gui.show( "gui7(DEWARP_SETTINGS,,,-1,%s)" % ",".join(str(x) for x in self.chan_on_template), self.attention_monitor, ) except Exception as e: logger.debug("ERROR to assign channels: %s" % e) host.timeout(1000 * self.time_to_del, self.del_old)
def start(self): now = datetime.now() if now - self.dt_end > self._DELAY: if self.weekdays: weekday = now.weekday() + 1 if weekday in self.weekdays: saver.video_export(self.dt_start, self.dt_end) else: saver.video_export(self.dt_start, self.dt_end) self.dt_start += self._day self.dt_end += self._day host.timeout(120 * 1000, self.start) else: host.timeout(60 * 1000, self.start)
def _loop_timer(self): now = time.time() for server_guid, down_time in self.disconnected_servers.items(): if now - down_time >= self.delay_before_start: logger.debug( "time to enable reversed devices for server %s", obj_storage.servers.get(server_guid), ) del self.disconnected_servers[server_guid] self._enable_reserved_devices(server_guid) host.stats()["run_count"] += 1 if self.disconnected_servers: host.timeout(1000, self._loop_timer) else: self._launch_running = False
def _timer(self): if self.ts_to_come_back < time.time(): logger.debug("time to close the gate. %s < %s", self.ts_to_come_back, time.time()) self.last_method() self.open_flag = False self.task_count -= 1 logger.debug("gate task count decreased, task count is: %s", self.task_count) if self.task_count < 0: logger.warning("Task count couldn't be negative ") self.task_count = 0 if self.task_count: host.timeout(2000, self.next_iteration) else: host.timeout(1000, self._timer)
def _work_iteration(self): logger.debug("Work iteration") now = datetime.datetime.now() time_now = self.time_now(now) delay = 30 with lock: if self._is_time_to_reset_counter(time_now): logger.info("Reset peoples current value to 0") self.config.peoples_current.value = 0 delay *= 3 config.save() if self.working: host.timeout(1000 * delay, self._work_iteration)
def _load_object(self, tries=5): logger.debug("Loading schedule object('%s')...", self._name) for sett in host.settings("scripts").ls(): if sett.type == "Schedule" and sett["enable"] and ( sett.name == self._name or sett.guid == self._name): obj = host.object(sett.guid) logger.debug("Found local schedule %s", sett.guid) break else: logger.warning( "Local schedule not found, get random global object with name %r", self._name) obj = host.object(self._name) try: self._name = obj.name try: obj.state("color") logger.info("Schedule %s (%s) loaded success", obj.name, obj.guid) except KeyError: raise RuntimeError( "Object {obj.name} ({obj.guid}) is not schedule".format( obj=obj)) self.__obj = obj self.__prev_color = self.color if callable(self.color_change_handler): logger.info("Add handler on color changed") host.register_finalizer(self.__del__) # Call handler with timeout need to fix bug: # Restarting schedule with not Green color # calls state changes handler twice: # with Green color and current color self.__obj.activate_on_state_changes( lambda: host.timeout(1, self._state_changes)) except EnvironmentError: if tries: logger.warning("Schedule %s not found, next try after 1000ms", self._name) host.timeout(1000, lambda: self._load_object(tries - 1)) else: raise EnvironmentError( "Schedule with name {} not found".format(self._name))
def check_zones_with_objects_presence(self): """ Check long presence of an objects on the zones. Works in a loop """ if not self.presence_check: return logger.debug("simt_zones:: {}".format(self.zones_with_objects_presense)) for zone in self.zones_with_objects_presense: try: if ( host.object(zone["guid"]).state("objects_inside") != "No Objects in Zone" ): zone["timer"] += 1 if zone["timer"] > self.presence_delay: channel = zone["channel_guid"] event_type = "Object presence alarm" zone_or_border = zone["zone_guid"] tmstmp = int(time.time()) zone["timer"] = 0 logger.debug( "Object long-lasting presence alarm on channel: {}, zone: {}".format( host.object(channel).name, host.object(zone_or_border).name, ) ) alarm_messages = make_alarm_message( channel, event_type, zone_or_border, tmstmp ) if self.callback: self.callback(channel, tmstmp, event_type, alarm_messages) else: zone["timer"] = 0 except KeyError: self.zones_with_objects_presense.remove(zone) host.timeout(1000, self.check_zones_with_objects_presence)
def run(self): """ Run the job and immediately reschedule it. :return: The return value returned by the `job_func` """ logger.info('Running job %s', self) # ret = self.job_func() ret = host.timeout(0, self.job_func) self.last_run = datetime.datetime.now() self._schedule_next_run() return ret
def __async_shot(self, channel_full_guid, file_name, file_path, ts, created_ts, figures, callback, task_guid): method = host.screenshot_v2_figures if figures else host.screenshot_v2 if time.time() >= created_ts: for _ in xrange(self.max_tries): host.timeout(10, lambda: callback(task_guid, status.saving)) method(channel_full_guid, file_name, file_path, ts) if self.__is_file_exists(os.path.join(file_path, file_name), timeout=self.timeout_sec): host.timeout(10, lambda: callback(task_guid, status.success)) break else: host.timeout(10, lambda: callback(task_guid, status.error)) else: self.__thread_pool.add_task( self.__async_shot, channel_full_guid, file_name, file_path, ts, created_ts, figures, callback, task_guid, )
def _show_channels_on_display(self): """ Запускается при изменении в списке каналов для отображения, именно здесь происходит работа с методами Trassir Returns: """ if not self._displaying_channels: # Нет тревожных каналов для отображения self.show_base_template() return if self.channels_for_same_cell: logger.debug("channels for same cell is True: %s", self.channels_for_same_cell) channels_to_show = ",".join( self._show_channels_with_static_cells()) else: channels_to_show = ",".join(list(self._displaying_channels)) logger.debug("assign channels: %s", channels_to_show) if self.show_timer_running: self._gui.assign_channels(channels_to_show, self.display_number) else: # Первый тревожный канал для отображения # если используем len(self._displaying_channels) == 1, то в случае, # когда количество каналов меняется с 2 до 1 show_template() не нужно self._gui.show_template(self.alarm_template, self.display_number) host.timeout( self.delay_before_assign, lambda: self._gui.assign_channels(channels_to_show, self. display_number), ) if not self.show_timer_running: self.show_timer()
def output_manager_loop(self): diff = time.time() - self.prev_oper_ts if diff > self.delay and self.prev_method == self.first_method: # внутри одной итерации, время вызвать второй метод (закрыть шлагбаум) logger.debug( "Inside the iteration. Time to close gate. Time passed since the last operation (%s) > delay (%s) ", time.time() - self.prev_oper_ts, self.delay, ) self.count -= 1 logger.debug("count decreased. count: %s", self.count) self.prev_oper_ts = time.time() _method_to_work = self.method_to_work.next() logger.debug( "method name: %s", _method_to_work.__name__, ) self.prev_method = _method_to_work _method_to_work() if self.count < 0: logger.warning("something goes wrong, count is: %s", self.count) self.count = 0 if self.count <= 0: logger.debug("all iterations were made, stop loop") self.loop_working = False else: logger.debug("host.timeout -- 1") host.timeout(1000, self.output_manager_loop) elif diff > self.delay_between_iterations and self.prev_method == self.last_method: # между итерациями, время вызвать первый метод (открыть шлагбаум) logger.debug( "Between two iterations. Time passed since the last iteration (%s)" " > delay_between_iterations (%s)", diff, self.delay_between_iterations) self.prev_oper_ts = time.time() _method_to_work = self.method_to_work.next() logger.debug( "method name: %s", _method_to_work.__name__, ) self.prev_method = _method_to_work _method_to_work() logger.debug("host.timeout -- 2") host.timeout(1000, self.output_manager_loop) else: # waiting logger.debug( "host.timeout -- 3. delay in action, going to check next loop") host.timeout(1000, self.output_manager_loop)
def _timeout_loop(): on_health_changes() host.timeout(TIMEOUT * 6e4, _timeout_loop)
def _timer(self): if self.ts_to_come_back < time.time(): self._normal() self.come_back_timer_is_working = False else: host.timeout(1000, self._timer)
def save( self, channel_full_guid, dt=None, figures=False, file_name=None, file_path=None, callback=None, task_guid=None, fmt=None, ): """Saving screenshot Args: channel_full_guid (str): Screenshot full guid, `channelGuid_serverGuid` dt (datetime.datetime, optional): Shot datetime, default current time figures (bool, optional): Trying to save shots with figures if True file_name (str, optional): Screenshot filename, default None file_path (str, optional): Path to save shot, default None callback (callable, optional): Callback after shot saved, default None task_guid (str, optional): Custom task guid, default None fmt (Dict[str: Any]): Used as kwargs for filename/filepath formatting Returns: Tuple[str, str]: task guid and file path """ task_guid = task_guid or host.random_guid() callback = callback or self.callback logger.debug( "ShotSaver.save(%r, dt=%r, figures=%r, file_name=%r, file_path=%r, callback=%r, task_guid=%r)", channel_full_guid, dt, figures, file_name, file_path, callback, task_guid, ) if "_" not in channel_full_guid: raise ValueError( "Expected full channel guid, got {}".format(channel_full_guid)) channel_guid, server_guid = channel_full_guid.split("_") try: server = host.settings( "/{server_guid}".format(server_guid=server_guid)) except KeyError: raise EnvironmentError( host.tr("Server %s not found") % server_guid) try: channel = host.settings( "/{server_guid}/channels/{channel_guid}".format( server_guid=server_guid, channel_guid=channel_guid)) except KeyError: raise EnvironmentError( host.tr("Channel %s not found on server %s") % (channel_guid, server.name)) if dt is None: ts = 0 dt = datetime.datetime.now() else: if not isinstance(dt, datetime.datetime): ts = dt try: dt = ts_to_dt(dt) except ValueError: raise ValueError( "Can't parse datetime from %s, try to use datetime.datetime instance" % dt) else: ts = dt_to_ts(dt) ts = str(ts) if fmt is None: fmt = {} file_name = (file_name or self.file_name_tmpl).format(channel=channel, server=server, **fmt) file_name = dt.strftime(file_name) file_path = (file_path or self.screenshots_folder).format(channel=channel, server=server, **fmt) file_path = dt.strftime(file_path) created_ts = time.time() + self.buffer_ts self.__check_path(file_path) self.__thread_pool.add_task( self.__async_shot, channel_full_guid, file_name, file_path, ts, created_ts, figures, callback, task_guid, ) host.timeout(10, lambda: callback(task_guid, status.in_queue)) return task_guid, _win_encode_path(os.path.join(file_path, file_name))