Exemplo n.º 1
0
def initialization():
    if CHAN_BAD:
        bad_list = [host.object(x).guid for x in CHAN_BAD.split(",")]
    else:
        bad_list = []
    logger.debug(bad_list)
    logger.debug(choice_dict[CHOICE])
    if CHAN:
        carousel_list = [
            host.object(x).guid
            for x in CHAN.split(",")
            if not host.object(x).guid in bad_list
        ]
    else:
        carousel_list = [
            x[1] for x in host.objects_list(choice_dict[CHOICE]) if not x[1] in bad_list
        ]
    logger.debug(carousel_list)
    for x in [z[1] for z in host.objects_list("IP Device")]:
        if x in carousel_list:
            raise ValueError(
                host.tr("Имеется IP устройство с именем канала %s") % host.object(x).name
            )
    logger.debug("list %s done!" % carousel_list)
    return {x: z for x, z in enumerate(carousel_list)}
Exemplo n.º 2
0
    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)
Exemplo n.º 3
0
    def get_object(cls, obj_id):
        """Возвращает объект Trassir, если он доступен, иначе ``None``

        Args:
            obj_id (:obj:`str`): Guid объекта или его имя

        Returns:
            :obj:`ScriptHost.SE_Object`: Объект Trassir или ``None``

        Examples:
            >>> obj = BaseUtils.get_object("EZJ4QnbC")
            >>> if obj is None:
            ...     host.error("Object not found")
            ... else:
            ...     host.message("Object name is {0.name}".format(obj))
        """
        if not isinstance(obj_id, (str, unicode)):
            raise TypeError("Expected str or unicode, got '{}'".format(
                type(obj_id).__name__))
        obj = host.object(obj_id)
        try:
            obj.name
        except EnvironmentError:
            # Object not found
            obj = None
        return obj
Exemplo n.º 4
0
    def __init__(self, name=None, guid=None, parent=None):
        super(ScriptObject, self).__init__("Script")

        scr_parent = host.stats().parent()

        self._name = name or SCRIPT_NAME
        self.set_name(self._name)

        self._guid = guid or "{}-object".format(scr_parent.guid)
        self.set_guid(self._guid)

        self._parent = parent or host.settings("").guid
        self.set_parent(self._parent)

        self._folder = ""

        self._health = "OK"
        self._check_me = True

        self.set_initial_state([self._health, self._check_me])

        host.object_add(self)

        self._obj = host.object(self._guid)

        self.context_menu = []
Exemplo n.º 5
0
 def __init__(
     self,
     alarm_template,
     base_template,
     display_number,
     max_channels,
     show_channel_duration,
     no_motion_check,
 ):
     self.alarm_template = alarm_template
     self.base_template = base_template
     self.display_number = display_number
     self.max_channels = max_channels
     self.show_channel_duration = show_channel_duration
     self.no_motion_check = no_motion_check
     self._gui = host.object("operatorgui_" + host.settings("").guid)
     self._CLEAN = "gui7(-1, '')"
     self._displaying_channels = OrderedDict()
     self.template_dropped = False
     self.show_timer_running = False
     logger.debug(
         "Display number is: %s, max channels is: %s",
         self.display_number,
         self.max_channels,
     )
Exemplo n.º 6
0
    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))
Exemplo n.º 7
0
 def attention(self, ev):
     guid = ev.origin
     if (host.object(guid).name not in self.carousel_dict
             and guid in self.chan_on_template):
         return
     self.chan_on_template.append(ev.origin)
     self.show_chans()
     pass
Exemplo n.º 8
0
 def __init__(self, carousel_dict, hand_using, func):
     self.chan_on_template = []
     self.gui = host.object("operatorgui_" + host.settings("").guid)
     self.carousel_dict = carousel_dict
     self.hand_using = hand_using
     self.func = func
     self.idx = 0
     self.carousel_go()
    def send(self, status, shot_path, alarm_messages, *args, **kwargs):
        """
                Args:
                   status (str): one of "saving", "error", "success", "in_queue"
                   shot_path (List['str']): ['Shot path 1', 'Shot path 2']
                   alarm_messages (dict):

               Returns:
        """
        self.contents = [
            {
                "type":
                "html",
                "html":
                ("<!doctype html><head><meta charset='utf-8'></head><body>"
                 ""
                 "{message}"
                 ""
                 "</body></html>").format(
                     message=alarm_messages.get('mail_message', 'No text')),
            },
        ]

        if kwargs.get("channel") and self.add_video:
            try:
                full_channel = kwargs.get("channel")
                channel, server = full_channel.split("_")
                self.contents.append({
                    "type": "trassir_channel",
                    "channel_guid": channel,
                    "name": host.object(channel).name,
                    "server_guid": server,
                })
            except IndexError:
                logger.debug(
                    "Can't get server name to make video content for alarm")

        if status == STATUS.success:
            logger.debug('try to send alarm')

            self.contents.append({
                "type":
                "image",
                "format":
                "jpg",
                "image_base64":
                BaseUtils.image_to_base64(shot_path[0]),
            })

            self.description = alarm_messages.get('mail_message', 'No text')
            super(FireAlarm, self).fire()

        elif status == STATUS.error:
            logger.debug('image not saved, try to send text alarm')
            self.description = alarm_messages.get('mail_message', 'No text')
            super(FireAlarm, self).fire()
Exemplo n.º 10
0
    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)
Exemplo n.º 11
0
    def __init__(
        self,
        alarm_template,
        am_type,
        max_channels,
        display_duration=30,
        base_template=None,
        no_motion_check=False,
        delay_before_assign=1500,
        channels_for_same_cell=None,
        all_displays=None,
    ):
        """
        Распределяет тревожные каналы по Тревожным мониторам.
        Максимальное количество мониторов 3.
        Сначала заполняется шаблон на одном мониторе, затем, по очереди заполняются
        шаблоны на других мониторах.
        Если на всех мониторах количество отображаемых каналов достигло максимального,
        то отправляем канал для отображения на следующий в очереди монитор.

        Задача класса распределять тревожные каналы равномерно по Тревожным мониторам.
        Args:
            alarm_template (str):
            am_type (int): 1 - show online, 2 - show archive
            max_channels (int):
            display_duration (int):
            base_template (str):
            no_motion_check (bool):
            channels_for_same_cell(dict|None): Every time show a channel in the same cell
             for it if same_cell is not empty
            all_displays (List(int)| None): display numbers list

        """
        self.alarm_template = alarm_template
        self.am_type = am_type
        self._max_channels = 1
        self.max_channels = max_channels
        self.base_template = base_template
        self.no_motion_check = no_motion_check  # TODO: add
        self.display_duration = display_duration
        self.delay_before_assign = delay_before_assign
        self.channels_for_same_cell = channels_for_same_cell
        self.all_displays = all_displays

        self._monitor_by_channel = None
        self._associated_channels_by_monitor_number = None
        self.associated_channels_by_monitor_number = channels_for_same_cell

        self.am_objects = {}
        self._am_before = None
        self._count = 0
        self._gui = host.object("operatorgui_" + host.settings("").guid)

        self.prepare_before_creation()
Exemplo n.º 12
0
def get_channels():
    channels = []
    for name, guid, _, parent in sorted(
        host.objects_list("Channel"), key=lambda x: (x[3], x[0])
    ):
        srv = host.object(parent[:-1])
        try:
            name = "%s@%s" % (name, srv.name)
        except EnvironmentError:
            name = "%s@%s" % (name, parent[:-1])
        channels.append((guid, name))
    return channels
Exemplo n.º 13
0
 def deep_people_border_filter(object_from_list):
     """ filtering border from deep_people """
     border_guid = object_from_list[1]
     border = host.object(border_guid)
     try:
         channel_guid, server_guid = border.associated_channel.split("_")
         zones_dir = host.settings("/%s/channels/%s/deep_people" % (server_guid, channel_guid))
         for i in xrange(16):
             if zones_dir["zone%02d_guid" % i] == border_guid:
                 return zones_dir["zone%02d_type" % i] == "border"
         return False
     except (ValueError, KeyError):
         return False
Exemplo n.º 14
0
    def __init__(self, attention_monitor, alarm_template_after, time_to_del):
        self.attention_monitor = attention_monitor
        self.operate_gui = host.object("operatorgui_" + host.settings("").guid)
        self.chan_on_template = []
        for tmpl in host.settings("templates").ls():
            if tmpl.type == "Template" and tmpl.name == alarm_template_after:
                alarm_template_after_content = tmpl["content"]
                break
        else:
            raise RuntimeError("Шаблон не найден")

        self.alarm_template_after = alarm_template_after
        self.alarm_template_after_content = alarm_template_after_content
        self.time_to_del = time_to_del
        self.time_dict = {}
Exemplo n.º 15
0
 def __init__(
     self,
     access_point_name,
     access_point_type,
     operation_type,
     delay_operations,
     show_message,
     show_message_delay,
 ):
     self.access_point_name = access_point_name
     self.access_point_obj = host.object(self.access_point_name)
     self.access_point_type = access_point_type
     self.operation_type = operation_type
     self.delay_operations = delay_operations
     self.show_message = show_message
     self.show_message_delay = show_message_delay
     self.ts_to_come_back = 0
     self.come_back_timer_is_working = False
Exemplo n.º 16
0
def get_data_from_channel(sett, server_guid):
    channel_info = {}
    for ch_number in xrange(31):
        if sett["channel%02d_guid" % ch_number]:
            try:
                ch_object = host.object(sett["channel%02d_guid" % ch_number])
                channel_info["ch_name"] = ch_object.name
                channel_info["motion_detector"] = type_motion_detector.get(
                    host.settings("/{}/channels/{}".format(
                        server_guid, ch_object.guid))["software_md_enable"],
                    "Unknown",
                )
            except EnvironmentError:
                logger.debug(
                    "Channel guid '%s' has no name, most likely the streams are disabled for the registrar channel",
                    sett["channel%02d_guid" % ch_number],
                )
                continue
            channel_info["codec"] = sett["channel%02d_codec" % ch_number]
            channel_info["audio_enabled"] = ("On" if
                                             sett["channel%02d_audio_enabled" %
                                                  ch_number] else "Off")
            channel_info["audio_codec"] = sett["channel%02d_audio_codec" %
                                               ch_number]
            channel_info["main"] = ("On" if sett["channel%02d_main_enabled" %
                                                 ch_number] else "Off")
            channel_info["main_fps"] = sett["channel%02d_fps" % ch_number]
            channel_info["main_gop"] = sett["channel%02d_gop" % ch_number]
            channel_info["main_resolution"] = sett["channel%02d_resolution" %
                                                   ch_number]
            channel_info["sub"] = ("On" if sett["channel%02d_ext_gop" %
                                                ch_number] else "Off")
            channel_info["sub_fps"] = sett["channel%02d_ext_fps" % ch_number]
            channel_info["sub_gop"] = sett["channel%02d_ext_gop" % ch_number]
            channel_info["sub_resolution"] = sett["channel%02d_ext_resolution"
                                                  % ch_number]
            logger.debug("channel info: %s", channel_info)

            yield channel_info
        else:
            break
Exemplo n.º 17
0
    def _replace_old(self):
        """Delete the oldest channel from the list before add new one
        """
        oldest_channel, event_info = next(
            self._displaying_channels.iteritems())
        min_time = event_info.get("start_to_show")

        for channel, event_info in self._displaying_channels.iteritems():
            if self.no_motion_check and host.object(channel).state("motion"):
                logger.debug("Motion detected on channel (%s), skip it",
                             channel)
                continue
            if event_info.get("start_to_show") < min_time:
                min_time = event_info.get("start_to_show")
                oldest_channel = channel
        logger.debug("deleting old channel: %s", oldest_channel)
        try:
            del self._displaying_channels[oldest_channel]
        except KeyError:
            logger.debug("can't delete _displaying_channels[%s]",
                         oldest_channel)
Exemplo n.º 18
0
    def __init__(self,
                 name=None,
                 guid=None,
                 parent="",
                 folder="",
                 associated_channel="",
                 **kwargs):
        self.__obj = None
        self.classname = self.classname or self.__class__.__name__

        self._folder = ""
        self._name = name or script.name
        self._guid = guid or "{}-object".format(script.guid)
        self._parent = parent

        self.__register_class_if_not_exists()
        super(BaseObject, self).__init__(self.classname)

        initial_state = getattr(self, "initial_state", None)
        if initial_state is None:
            initial_state = []
            if self.states:
                for state in self.states:
                    initial_state.append(state.values[0].value)

        self.set_name(self._name)
        self.set_guid(self._guid)
        self.set_parent(self._parent)
        self.set_initial_state(initial_state)
        if associated_channel:
            self.set_associated_channel(str(associated_channel))

        host.object_add(self)

        self.__obj = host.object(self._guid)

        if folder:
            self.folder = folder

        self.context_menu = []
Exemplo n.º 19
0
    def __init__(
        self,
        alarm_template,
        am_type,
        max_channels,
        display_duration=30,
        base_template=None,
        no_motion_check=False,
    ):
        """
        Распределяет тревожные каналы по Тревожным мониторам.
        Максимальное количество мониторов 3.
        Сначала заполняется шаблон на одном мониторе, затем, по очереди заполняются
        шаблоны на других мониторах.
        Если на всех мониторах количество отображаемых каналов достигло максимального,
        то отправляем канал для отображения на следующий в очереди монитор.

        Задача класса распределять тревожные каналы равномерно по Тревожным мониторам.
        Args:
            alarm_template (str):
            am_type (int): 1 - show online, 2 - show archive
            max_channels (int):
            display_duration (int):
            base_template (str):
            no_motion_check (bool):
            am_type (str): host.tr("Отобразить канал") | host.tr("Открыть момент в архиве")
        """
        self.alarm_template = alarm_template
        self.am_type = am_type
        self._max_channels = 1
        self.max_channels = max_channels
        self.base_template = base_template
        self.no_motion_check = no_motion_check  # TODO: add
        self.display_duration = display_duration

        self.am_objects = None
        self._am_before = None
        self._count = 0
        self._gui = host.object("operatorgui_" + host.settings("").guid)
Exemplo n.º 20
0
    def __init__(
        self,
        access_point_name,
        access_point_type,
        operation_type,
        delay_operations,
    ):
        """
        Args:
            access_point_name (str):
            access_point_type (str): "Sigur" or "Orion"
            operation_type (str): host.tr("открыть дверь") or host.tr("закрыть дверь")
            delay_operations (int):
        """
        self.access_point_name = access_point_name
        self.access_point_obj = host.object(self.access_point_name)
        self.access_point_type = access_point_type
        self.operation_type = operation_type
        self.delay_operations = delay_operations

        self.ts_to_come_back = 0
        self.come_back_timer_is_working = False
Exemplo n.º 21
0
    def __init__(
        self,
        access_point_name,
        access_point_type,
        operation_type,
        delay_operations,
    ):
        """
        Args:
            access_point_name (str):
            access_point_type (str):"Sigur" or "Orion"
            operation_type (str): "open the door" or "close_th_door"
            delay_operations (int):
        """
        self.access_point_name = access_point_name
        self.access_point_obj = host.object(self.access_point_name)
        self.access_point_type = access_point_type
        self.operation_type = operation_type
        self.delay_operations = delay_operations

        self.ts_to_come_back = 0
        self.come_back_timer_is_working = False
Exemplo n.º 22
0
def get_outputs(names=None):
    """

    Args:
        names (set):

    Returns:

    """
    _gpios = []
    for x in host.objects_list("GPIO Output"):
        if names and x[0] not in names:
            continue
        obj = host.object(x[1])
        if hasattr(obj, "set_output_high") and hasattr(obj, "set_output_low"):
            try:
                name = obj.name
                guid = obj.guid
            except EnvironmentError:
                raise EnvironmentError(
                    "Can't get access to %s, check script user rights" % x[0])
            else:
                _gpios.append(OutputObj(obj, name, guid, x[3]))
    return _gpios
Exemplo n.º 23
0
            host.activate_on_shortcut(
                OUTPUT_MAN_ACTIV,
                output_reactions.manual_activation_of_outputs)

    # -------------------------------------------------------
    # Operations with physical system control ("СКУД")
    # -------------------------------------------------------

    if ACS_ENBL:
        from reactions import AccessControlOperations

        assert ACS_TYPE in ["Sigur",
                            "Orion"], "ACS_TYPE must be Sigur or Orion"
        assert ACS_DOOR, host.tr("Необходимо указать название точки доступа")

        acs_door_obj = host.object(ACS_DOOR)

        if ACS_TYPE == "Sigur":
            assert hasattr(
                acs_door_obj, "workmode_alwaysopen"
            ), "{} не является точкой доступа Sigur. Только одно имя м.б. указано".format(
                ACS_DOOR)
        if ACS_TYPE == "Orion":
            assert hasattr(
                acs_door_obj, "grant_access_once"
            ), "{} не является точкой доступа Orion. Только одно имя м.б. указано".format(
                ACS_DOOR)

        assert ACS_LOGIC in [
            host.tr("открыть дверь"),
            host.tr("закрыть дверь"),
Exemplo n.º 24
0
        <id>SERVER_GUID</id>
        <type>server</type>
        <name>Server</name>
        <value></value>
    </parameter>
    <parameter>
        <id>MODULE_LINK</id>
        <type>string</type>
        <name>Module</name>
        <value>FaceWorkTime</value>
    </parameter>
</parameters>
"""

GLOBALS = globals()

SERVER_GUID = GLOBALS.get("SERVER_GUID", "")
MODULE_LINK = GLOBALS.get("MODULE_LINK", "FaceWorkTime")

assert SERVER_GUID, "Server not selected"

import host

gui = host.object('operatorgui_%s' % host.settings('').guid)

source = "%s_%s" % (host.stats().parent().guid, MODULE_LINK)
link = "http://exthttp/{server_guid}/{module_link}".format(
    server_guid=SERVER_GUID, module_link=MODULE_LINK
)

host.activate_on_shortcut("F1", lambda: gui.show_html(source, link))
Exemplo n.º 25
0
 def __init__(self, monitor_to_show_archive_from_popup):
     self.monitor_to_show_archive_from_popup = monitor_to_show_archive_from_popup
     self._gui = host.object("operatorgui_" + host.settings('').guid)
Exemplo n.º 26
0
import time
import random
from itertools import cycle
from __builtin__ import object

import host

import helpers

helpers.set_script_name()
logger = helpers.init_logger(APP_NAME, debug=DEBUG)

from schedule import ScheduleObject

assert CHANNEL, "Channel not selected"
channel = host.object(CHANNEL.split("_")[0])
try:
    channel.state("signal")
except EnvironmentError:
    raise EnvironmentError("Channel %s not found or disabled" % CHANNEL)


def __get_random_timout():
    return random.randint(PATROL_PRESET_TIMEOUT,
                          PATROL_PRESET_TIMEOUT_RAND_MAX)


if PATROL_PRESET_TIMEOUT == PATROL_PRESET_TIMEOUT_RAND_MAX:

    def get_timeout():
        return PATROL_PRESET_TIMEOUT
Exemplo n.º 27
0
    except KeyError:
        raise RuntimeError(
            "Не доступны настройки севрера, проверьте настройки дсотупа пользователя Script"
        )

    for route in media_route.split(":"):
        if route.startswith("ip="):
            module_host = route[3:]
            break
    else:
        raise RuntimeError(
            "IP сервера %s не найден, возможно вы подключены к серверу через облако<br>"
            "media_route: %s" % (server.name, media_route))

try:
    gui = host.object("operatorgui_%s" % local_server.guid)
    host.message("%s laoded success" % gui.name)
except EnvironmentError:
    raise EnvironmentError("OpertatorGUI is not available")


def show_minibrowser():
    gui.show(
        "minibrowser(0,htmltab(,http://{host}:{port}))".format(
            host=module_host, port=PORT),
        MONITOR,
    )


host.activate_on_shortcut(USER_FUNC, show_minibrowser)
Exemplo n.º 28
0
 def get_object_name(guid):
     try:
         return host.object(guid).name
     except EnvironmentError:
         return guid
Exemplo n.º 29
0
 def __init__(self, monitor_to_show_archive_from_popup, display_duration):
     self.monitor_to_show_archive_from_popup = monitor_to_show_archive_from_popup
     self.display_duration = display_duration
     self._gui = host.object("operatorgui_" + host.settings('').guid)