示例#1
0
    def __init__(self, device_info):
        """Initialize a Foscam camera."""
        from libpyfoscam import FoscamCamera

        super(FoscamCam, self).__init__()

        ip_address = device_info.get(CONF_IP)
        port = device_info.get(CONF_PORT)
        self._username = device_info.get(CONF_USERNAME)
        self._password = device_info.get(CONF_PASSWORD)
        self._name = device_info.get(CONF_NAME)
        self._motion_status = False

        self._foscam_session = FoscamCamera(ip_address,
                                            port,
                                            self._username,
                                            self._password,
                                            verbose=False)

        self._rtsp_port = device_info.get(CONF_RTSP_PORT)
        if not self._rtsp_port:
            result, response = self._foscam_session.get_port_info()
            if result == 0:
                self._rtsp_port = response.get('rtspPort') or \
                                  response.get('mediaPort')
示例#2
0
class FoscamCam(Camera):
    """An implementation of a Foscam IP camera."""
    def __init__(self, device_info):
        """Initialize a Foscam camera."""
        from libpyfoscam import FoscamCamera

        super(FoscamCam, self).__init__()

        ip_address = device_info.get(CONF_IP)
        port = device_info.get(CONF_PORT)
        self._username = device_info.get(CONF_USERNAME)
        self._password = device_info.get(CONF_PASSWORD)
        self._name = device_info.get(CONF_NAME)
        self._motion_status = False

        self._foscam_session = FoscamCamera(ip_address,
                                            port,
                                            self._username,
                                            self._password,
                                            verbose=False)

    def camera_image(self):
        """Return a still image response from the camera."""
        # Send the request to snap a picture and return raw jpg data
        # Handle exception if host is not reachable or url failed
        result, response = self._foscam_session.snap_picture_2()
        if result == FOSCAM_COMM_ERROR:
            return None

        return response

    @property
    def motion_detection_enabled(self):
        """Camera Motion Detection Status."""
        return self._motion_status

    def enable_motion_detection(self):
        """Enable motion detection in camera."""
        try:
            ret = self._foscam_session.enable_motion_detection()
            self._motion_status = ret == FOSCAM_COMM_ERROR
        except TypeError:
            _LOGGER.debug("Communication problem")
            self._motion_status = False

    def disable_motion_detection(self):
        """Disable motion detection."""
        try:
            ret = self._foscam_session.disable_motion_detection()
            self._motion_status = ret == FOSCAM_COMM_ERROR
        except TypeError:
            _LOGGER.debug("Communication problem")
            self._motion_status = False

    @property
    def name(self):
        """Return the name of this camera."""
        return self._name
示例#3
0
class FoscamCam(Camera):
    """An implementation of a Foscam IP camera."""

    def __init__(self, device_info):
        """Initialize a Foscam camera."""
        from libpyfoscam import FoscamCamera

        super(FoscamCam, self).__init__()

        ip_address = device_info.get(CONF_IP)
        port = device_info.get(CONF_PORT)
        self._username = device_info.get(CONF_USERNAME)
        self._password = device_info.get(CONF_PASSWORD)
        self._name = device_info.get(CONF_NAME)
        self._motion_status = False

        self._foscam_session = FoscamCamera(
            ip_address, port, self._username, self._password, verbose=False)

    def camera_image(self):
        """Return a still image response from the camera."""
        # Send the request to snap a picture and return raw jpg data
        # Handle exception if host is not reachable or url failed
        result, response = self._foscam_session.snap_picture_2()
        if result == FOSCAM_COMM_ERROR:
            return None

        return response

    @property
    def motion_detection_enabled(self):
        """Camera Motion Detection Status."""
        return self._motion_status

    def enable_motion_detection(self):
        """Enable motion detection in camera."""
        try:
            ret = self._foscam_session.enable_motion_detection()
            self._motion_status = ret == FOSCAM_COMM_ERROR
        except TypeError:
            _LOGGER.debug("Communication problem")
            self._motion_status = False

    def disable_motion_detection(self):
        """Disable motion detection."""
        try:
            ret = self._foscam_session.disable_motion_detection()
            self._motion_status = ret == FOSCAM_COMM_ERROR
        except TypeError:
            _LOGGER.debug("Communication problem")
            self._motion_status = False

    @property
    def name(self):
        """Return the name of this camera."""
        return self._name
    def __init__(self, device_info):
        """Initialize a Foscam camera."""
        super(FoscamCam, self).__init__()

        ip_address = device_info.get(CONF_IP)
        port = device_info.get(CONF_PORT)
        self._username = device_info.get(CONF_USERNAME)
        self._password = device_info.get(CONF_PASSWORD)
        self._name = device_info.get(CONF_NAME)
        self._motion_status = False

        from libpyfoscam import FoscamCamera

        self._foscam_session = FoscamCamera(ip_address, port, self._username,
                                            self._password, verbose=False)
示例#5
0
    async def _validate_and_create(self, data):
        """Validate the user input allows us to connect.

        Data has the keys from DATA_SCHEMA with values provided by the user.
        """
        camera = FoscamCamera(
            data[CONF_HOST],
            data[CONF_PORT],
            data[CONF_USERNAME],
            data[CONF_PASSWORD],
            verbose=False,
        )

        # Validate data by sending a request to the camera
        ret, response = await self.hass.async_add_executor_job(
            camera.get_dev_info)

        if ret == ERROR_FOSCAM_UNAVAILABLE:
            raise CannotConnect

        if ret == ERROR_FOSCAM_AUTH:
            raise InvalidAuth

        await self.async_set_unique_id(response["mac"])
        self._abort_if_unique_id_configured()

        name = data.pop(CONF_NAME, response["devName"])

        return self.async_create_entry(title=name, data=data)
示例#6
0
文件: camera.py 项目: mduran80/core
async def async_setup_entry(hass, config_entry, async_add_entities):
    """Add a Foscam IP camera from a config entry."""
    platform = entity_platform.current_platform.get()
    platform.async_register_entity_service(
        SERVICE_PTZ,
        {
            vol.Required(ATTR_MOVEMENT): vol.In(
                [
                    DIR_UP,
                    DIR_DOWN,
                    DIR_LEFT,
                    DIR_RIGHT,
                    DIR_TOPLEFT,
                    DIR_TOPRIGHT,
                    DIR_BOTTOMLEFT,
                    DIR_BOTTOMRIGHT,
                ]
            ),
            vol.Optional(ATTR_TRAVELTIME, default=DEFAULT_TRAVELTIME): cv.small_float,
        },
        "async_perform_ptz",
    )

    camera = FoscamCamera(
        config_entry.data[CONF_HOST],
        config_entry.data[CONF_PORT],
        config_entry.data[CONF_USERNAME],
        config_entry.data[CONF_PASSWORD],
        verbose=False,
    )

    async_add_entities([HassFoscamCamera(camera, config_entry)])
示例#7
0
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
    """Set up a Foscam IP Camera."""

    async def async_handle_ptz(service):
        """Handle PTZ service call."""
        movement = service.data[ATTR_MOVEMENT]
        travel_time = service.data[ATTR_TRAVELTIME]
        entity_ids = await async_extract_entity_ids(hass, service)

        if not entity_ids:
            return

        _LOGGER.debug("Moving '%s' camera(s): %s", movement, entity_ids)

        all_cameras = hass.data[FOSCAM_DATA][FOSCAM_ENTITIES]
        target_cameras = [
            camera for camera in all_cameras if camera.entity_id in entity_ids
        ]

        for camera in target_cameras:
            await camera.async_perform_ptz(movement, travel_time)

    hass.services.async_register(
        FOSCAM_DOMAIN, SERVICE_PTZ, async_handle_ptz, schema=SERVICE_PTZ_SCHEMA
    )

    camera = FoscamCamera(
        config[CONF_IP],
        config[CONF_PORT],
        config[CONF_USERNAME],
        config[CONF_PASSWORD],
        verbose=False,
    )

    rtsp_port = config.get(CONF_RTSP_PORT)
    if not rtsp_port:
        ret, response = await hass.async_add_executor_job(camera.get_port_info)

        if ret == 0:
            rtsp_port = response.get("rtspPort") or response.get("mediaPort")

    ret, response = await hass.async_add_executor_job(camera.get_motion_detect_config)

    motion_status = False
    if ret != 0 and response == 1:
        motion_status = True

    async_add_entities(
        [
            HassFoscamCamera(
                camera,
                config[CONF_NAME],
                config[CONF_USERNAME],
                config[CONF_PASSWORD],
                rtsp_port,
                motion_status,
            )
        ]
    )
示例#8
0
async def async_setup_platform(hass,
                               config,
                               async_add_entities,
                               discovery_info=None):
    """Set up a Foscam IP Camera."""
    platform = entity_platform.current_platform.get()
    assert platform is not None
    platform.async_register_entity_service(
        "ptz",
        {
            vol.Required(ATTR_MOVEMENT):
            vol.In([
                DIR_UP,
                DIR_DOWN,
                DIR_LEFT,
                DIR_RIGHT,
                DIR_TOPLEFT,
                DIR_TOPRIGHT,
                DIR_BOTTOMLEFT,
                DIR_BOTTOMRIGHT,
            ]),
            vol.Optional(ATTR_TRAVELTIME, default=DEFAULT_TRAVELTIME):
            cv.small_float,
        },
        "async_perform_ptz",
    )

    camera = FoscamCamera(
        config[CONF_IP],
        config[CONF_PORT],
        config[CONF_USERNAME],
        config[CONF_PASSWORD],
        verbose=False,
    )

    rtsp_port = config.get(CONF_RTSP_PORT)
    if not rtsp_port:
        ret, response = await hass.async_add_executor_job(camera.get_port_info)

        if ret == 0:
            rtsp_port = response.get("rtspPort") or response.get("mediaPort")

    ret, response = await hass.async_add_executor_job(
        camera.get_motion_detect_config)

    motion_status = False
    if ret != 0 and response == 1:
        motion_status = True

    async_add_entities([
        HassFoscamCamera(
            camera,
            config[CONF_NAME],
            config[CONF_USERNAME],
            config[CONF_PASSWORD],
            rtsp_port,
            motion_status,
        )
    ])
    def __init__(self, device_info):
        # pylint: disable=no-member
        from libpyfoscam import FoscamCamera

        super(FoscamCamMotion, self).__init__()

        ip_address = device_info.get(CONF_IP)
        port = device_info.get(CONF_PORT)
        self._username = device_info.get(CONF_USERNAME)
        self._password = device_info.get(CONF_PASSWORD)
        self._name = device_info.get(CONF_NAME)

        self._available = False
        self._state = False

        self._foscam_session = FoscamCamera(ip_address,
                                            port,
                                            self._username,
                                            self._password,
                                            verbose=True)
示例#10
0
    async def _validate_and_create(self, data):
        """Validate the user input allows us to connect.

        Data has the keys from DATA_SCHEMA with values provided by the user.
        """

        for entry in self.hass.config_entries.async_entries(DOMAIN):
            if (
                entry.data[CONF_HOST] == data[CONF_HOST]
                and entry.data[CONF_PORT] == data[CONF_PORT]
            ):
                raise AbortFlow("already_configured")

        camera = FoscamCamera(
            data[CONF_HOST],
            data[CONF_PORT],
            data[CONF_USERNAME],
            data[CONF_PASSWORD],
            verbose=False,
        )

        # Validate data by sending a request to the camera
        ret, _ = await self.hass.async_add_executor_job(camera.get_product_all_info)

        if ret == ERROR_FOSCAM_UNAVAILABLE:
            raise CannotConnect

        if ret == ERROR_FOSCAM_AUTH:
            raise InvalidAuth

        if ret != FOSCAM_SUCCESS:
            LOGGER.error(
                "Unexpected error code from camera %s:%s: %s",
                data[CONF_HOST],
                data[CONF_PORT],
                ret,
            )
            raise InvalidResponse

        # Try to get camera name (only possible with admin account)
        ret, response = await self.hass.async_add_executor_job(camera.get_dev_info)

        dev_name = response.get(
            "devName", f"Foscam {data[CONF_HOST]}:{data[CONF_PORT]}"
        )

        name = data.pop(CONF_NAME, dev_name)

        return self.async_create_entry(title=name, data=data)
示例#11
0
    def __init__(self, device_info):
        """Initialize a Foscam camera."""
        from libpyfoscam import FoscamCamera

        super(FoscamCam, self).__init__()

        ip_address = device_info.get(CONF_IP)
        port = device_info.get(CONF_PORT)
        self._username = device_info.get(CONF_USERNAME)
        self._password = device_info.get(CONF_PASSWORD)
        self._name = device_info.get(CONF_NAME)
        self._motion_status = False

        self._foscam_session = FoscamCamera(
            ip_address, port, self._username, self._password, verbose=False)
示例#12
0
async def async_migrate_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Migrate old entry."""
    LOGGER.debug("Migrating from version %s", entry.version)

    if entry.version == 1:
        # Change unique id
        @callback
        def update_unique_id(entry):
            return {"new_unique_id": entry.entry_id}

        await async_migrate_entries(hass, entry.entry_id, update_unique_id)

        entry.unique_id = None

        # Get RTSP port from the camera or use the fallback one and store it in data
        camera = FoscamCamera(
            entry.data[CONF_HOST],
            entry.data[CONF_PORT],
            entry.data[CONF_USERNAME],
            entry.data[CONF_PASSWORD],
            verbose=False,
        )

        ret, response = await hass.async_add_executor_job(camera.get_port_info)

        rtsp_port = DEFAULT_RTSP_PORT

        if ret != 0:
            rtsp_port = response.get("rtspPort") or response.get("mediaPort")

        hass.config_entries.async_update_entry(
            entry, data={
                **entry.data, CONF_RTSP_PORT: rtsp_port
            })

        # Change entry version
        entry.version = 2

    LOGGER.info("Migration to version %s successful", entry.version)

    return True
示例#13
0
    def __init__(self, device_info):
        """Initialize a Foscam camera."""
        from libpyfoscam import FoscamCamera

        super(FoscamCam, self).__init__()

        ip_address = device_info.get(CONF_IP)
        port = device_info.get(CONF_PORT)
        self._username = device_info.get(CONF_USERNAME)
        self._password = device_info.get(CONF_PASSWORD)
        self._name = device_info.get(CONF_NAME)
        self._motion_status = False

        self._foscam_session = FoscamCamera(
            ip_address, port, self._username, self._password, verbose=False)

        self._rtsp_port = None
        result, response = self._foscam_session.get_port_info()
        if result == 0:
            self._rtsp_port = response.get('rtspPort') or \
                              response.get('mediaPort')
class FoscamCamMotion(BinarySensorDevice):
    """Represent a binary sensor that uses Raspberry Pi GPIO via gpiozero"""
    def __init__(self, device_info):
        # pylint: disable=no-member
        from libpyfoscam import FoscamCamera

        super(FoscamCamMotion, self).__init__()

        ip_address = device_info.get(CONF_IP)
        port = device_info.get(CONF_PORT)
        self._username = device_info.get(CONF_USERNAME)
        self._password = device_info.get(CONF_PASSWORD)
        self._name = device_info.get(CONF_NAME)

        self._available = False
        self._state = False

        self._foscam_session = FoscamCamera(ip_address,
                                            port,
                                            self._username,
                                            self._password,
                                            verbose=True)

    @property
    def should_poll(self):
        return True

    @property
    def name(self):
        """Return the name of the sensor."""
        return self._name

    @property
    def is_on(self):
        """Return the state of the entity."""
        return self._state

    @property
    def available(self):
        return self._available

    @property
    def device_class(self):
        return DEVICE_CLASS_MOTION

    def update(self):
        """Update the GPIO state."""
        _LOGGER.info("Updating %s", self._name)
        try:
            self._dev_state = self._foscam_session.get_dev_state()
            _LOGGER.info("DEV STATE %s", self._dev_state)
            if self._dev_state[0] == 0:
                motionDetectAlarm = int(
                    self._dev_state[1]['motionDetectAlarm'])
                if motionDetectAlarm == 1:
                    self._available = True
                    self._state = False
                elif motionDetectAlarm == 2:
                    self._available = True
                    self._state = True
                else:
                    self._available = False
                    self._state = False
            else:
                self._available = False
                self._state = False
        except:
            # If there are any errors during checking is_pressed
            # reset the _btn
            _LOGGER.exception("%s has failed to update", self._name)

        _LOGGER.info("%s has been updated to state %s available %s",
                     self._name, self._state, self._available)
示例#15
0
class FoscamCam(Camera):
    """An implementation of a Foscam IP camera."""

    def __init__(self, device_info):
        """Initialize a Foscam camera."""
        from libpyfoscam import FoscamCamera

        super().__init__()

        ip_address = device_info.get(CONF_IP)
        port = device_info.get(CONF_PORT)
        self._username = device_info.get(CONF_USERNAME)
        self._password = device_info.get(CONF_PASSWORD)
        self._name = device_info.get(CONF_NAME)
        self._motion_status = False

        self._foscam_session = FoscamCamera(
            ip_address, port, self._username, self._password, verbose=False
        )

        self._rtsp_port = device_info.get(CONF_RTSP_PORT)
        if not self._rtsp_port:
            result, response = self._foscam_session.get_port_info()
            if result == 0:
                self._rtsp_port = response.get("rtspPort") or response.get("mediaPort")

    def camera_image(self):
        """Return a still image response from the camera."""
        # Send the request to snap a picture and return raw jpg data
        # Handle exception if host is not reachable or url failed
        result, response = self._foscam_session.snap_picture_2()
        if result == FOSCAM_COMM_ERROR:
            return None

        return response

    @property
    def supported_features(self):
        """Return supported features."""
        if self._rtsp_port:
            return SUPPORT_STREAM
        return 0

    async def stream_source(self):
        """Return the stream source."""
        if self._rtsp_port:
            return "rtsp://{}:{}@{}:{}/videoMain".format(
                self._username,
                self._password,
                self._foscam_session.host,
                self._rtsp_port,
            )
        return None

    @property
    def motion_detection_enabled(self):
        """Camera Motion Detection Status."""
        return self._motion_status

    def enable_motion_detection(self):
        """Enable motion detection in camera."""
        try:
            ret = self._foscam_session.enable_motion_detection()
            self._motion_status = ret == FOSCAM_COMM_ERROR
        except TypeError:
            _LOGGER.debug("Communication problem")
            self._motion_status = False

    def disable_motion_detection(self):
        """Disable motion detection."""
        try:
            ret = self._foscam_session.disable_motion_detection()
            self._motion_status = ret == FOSCAM_COMM_ERROR
        except TypeError:
            _LOGGER.debug("Communication problem")
            self._motion_status = False

    @property
    def name(self):
        """Return the name of this camera."""
        return self._name