async def run(self, broker: str, listen: str, connect: str) -> None:
        p = urlparse(broker, scheme="mqtt")
        if p.scheme not in ("mqtt", "mqtts") or not p.hostname:
            raise ValueError

        tls_context = None
        if p.scheme == "mqtts":
            tls_context = ssl.create_default_context()

        will = None
        async with Client(
                p.hostname,
                port=p.port or p.scheme == "mqtt" and 1883 or 8883,
                username=p.username,
                password=p.password,
                logger=logger,
                tls_context=tls_context,
                will=will,
        ) as mqtt:
            xmlrpc_local = self._xmlrpc_listen_url(listen)
            xmlrpc_remote = self._xmlrpc_connect_url(connect)
            homematic = HMConnection(
                interface_id=HM_INTERFACE_ID,
                local=xmlrpc_local.hostname,
                localport=xmlrpc_local.port or 0,
                remotes={
                    HM_REMOTE: {
                        "ip": xmlrpc_remote.hostname,
                        "port": xmlrpc_remote.port,
                        "path": xmlrpc_remote.path or "",
                        "username": xmlrpc_remote.username or "Admin",
                        "password": xmlrpc_remote.password or "",
                    }
                },
                eventcallback=partial(self._event_callback, mqtt),
                systemcallback=partial(self._system_callback, mqtt),
            )

            try:
                homematic.start()
            except AttributeError:
                sys.exit(1)

            async with mqtt.unfiltered_messages() as messages:
                async for message in messages:
                    await self._process_packet(message, homematic)

            homematic.stop()
Beispiel #2
0
def setup(hass, config):
    """Setup the Homematic component."""
    global HOMEMATIC, HOMEMATIC_LINK_DELAY

    from pyhomematic import HMConnection

    local_ip = config[DOMAIN][0].get(CONF_LOCAL_IP)
    local_port = config[DOMAIN][0].get(CONF_LOCAL_PORT)
    remote_ip = config[DOMAIN][0].get(CONF_REMOTE_IP)
    remote_port = config[DOMAIN][0].get(CONF_REMOTE_PORT)
    resolvenames = config[DOMAIN][0].get(CONF_RESOLVENAMES)
    username = config[DOMAIN][0].get(CONF_USERNAME)
    password = config[DOMAIN][0].get(CONF_PASSWORD)
    HOMEMATIC_LINK_DELAY = config[DOMAIN][0].get(CONF_DELAY)

    if remote_ip is None or local_ip is None:
        _LOGGER.error("Missing remote CCU/Homegear or local address")
        return False

    # Create server thread
    bound_system_callback = partial(system_callback_handler, hass, config)
    HOMEMATIC = HMConnection(local=local_ip,
                             localport=local_port,
                             remote=remote_ip,
                             remoteport=remote_port,
                             systemcallback=bound_system_callback,
                             resolvenames=resolvenames,
                             rpcusername=username,
                             rpcpassword=password,
                             interface_id="homeassistant")

    # Start server thread, connect to peer, initialize to receive events
    HOMEMATIC.start()

    # Stops server when Homeassistant is shutting down
    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, HOMEMATIC.stop)
    hass.config.components.append(DOMAIN)

    # regeister homematic services
    descriptions = load_yaml_config_file(
        os.path.join(os.path.dirname(__file__), 'services.yaml'))

    hass.services.register(DOMAIN, SERVICE_VIRTUALKEY, _hm_service_virtualkey,
                           descriptions[DOMAIN][SERVICE_VIRTUALKEY],
                           SCHEMA_SERVICE_VIRTUALKEY)

    return True
Beispiel #3
0
def setup(hass, config):
    """Setup the Homematic component."""
    global HOMEMATIC, HOMEMATIC_LINK_DELAY

    from pyhomematic import HMConnection

    local_ip = config[DOMAIN].get("local_ip", None)
    local_port = config[DOMAIN].get("local_port", 8943)
    remote_ip = config[DOMAIN].get("remote_ip", None)
    remote_port = config[DOMAIN].get("remote_port", 2001)
    resolvenames = config[DOMAIN].get("resolvenames", False)
    username = config[DOMAIN].get("username", "Admin")
    password = config[DOMAIN].get("password", "")
    HOMEMATIC_LINK_DELAY = config[DOMAIN].get("delay", 0.5)

    if remote_ip is None or local_ip is None:
        _LOGGER.error("Missing remote CCU/Homegear or local address")
        return False

    # Create server thread
    bound_system_callback = partial(system_callback_handler, hass, config)
    HOMEMATIC = HMConnection(local=local_ip,
                             localport=local_port,
                             remote=remote_ip,
                             remoteport=remote_port,
                             systemcallback=bound_system_callback,
                             resolvenames=resolvenames,
                             rpcusername=username,
                             rpcpassword=password,
                             interface_id="homeassistant")

    # Start server thread, connect to peer, initialize to receive events
    HOMEMATIC.start()

    # Stops server when Homeassistant is shutting down
    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, HOMEMATIC.stop)
    hass.config.components.append(DOMAIN)

    return True
    def run(self, listen: str, connect: str) -> None:
        try:
            xmlrpc_local = self._xmlrpc_listen_url(listen)
            xmlrpc_remote = self._xmlrpc_connect_url(connect)
        except ValueError as exc:
            logger.error("Invalid XML-RPC URL: %s", exc)
            sys.exit(1)

        homematic = HMConnection(
            interface_id="inventory",
            local=xmlrpc_local.hostname,
            localport=xmlrpc_local.port or 0,
            remotes={
                "default": {
                    "ip": xmlrpc_remote.hostname,
                    "port": xmlrpc_remote.port,
                    "path": xmlrpc_remote.path or "",
                    "username": xmlrpc_remote.username or "Admin",
                    "password": xmlrpc_remote.password or "",
                }
            },
            eventcallback=self._event_callback,
            systemcallback=self._system_callback,
        )

        try:
            homematic.start()
        except AttributeError:
            sys.exit(1)

        def handler(signum, frame):
            signal(signum, SIG_DFL)
            homematic.stop()

        for signum in (SIGINT, SIGTERM):
            signal(signum, handler)

        homematic._server.join()
Beispiel #5
0
def setup(hass, config):
    """Set up the Homematic component."""
    from pyhomematic import HMConnection

    hass.data[DATA_DELAY] = config[DOMAIN].get(CONF_DELAY)
    hass.data[DATA_DEVINIT] = {}
    hass.data[DATA_STORE] = set()

    # Create hosts-dictionary for pyhomematic
    remotes = {}
    hosts = {}
    for rname, rconfig in config[DOMAIN][CONF_HOSTS].items():
        server = rconfig.get(CONF_IP)

        remotes[rname] = {}
        remotes[rname][CONF_IP] = server
        remotes[rname][CONF_PORT] = rconfig.get(CONF_PORT)
        remotes[rname][CONF_RESOLVENAMES] = rconfig.get(CONF_RESOLVENAMES)
        remotes[rname][CONF_USERNAME] = rconfig.get(CONF_USERNAME)
        remotes[rname][CONF_PASSWORD] = rconfig.get(CONF_PASSWORD)
        remotes[rname]['callbackip'] = rconfig.get(CONF_CALLBACK_IP)
        remotes[rname]['callbackport'] = rconfig.get(CONF_CALLBACK_PORT)

        if server not in hosts or rconfig.get(CONF_PRIMARY):
            hosts[server] = {
                CONF_VARIABLES: rconfig.get(CONF_VARIABLES),
                CONF_NAME: rname,
            }
        hass.data[DATA_DEVINIT][rname] = rconfig.get(CONF_DEVICES)

    # Create server thread
    bound_system_callback = partial(_system_callback_handler, hass, config)
    hass.data[DATA_HOMEMATIC] = HMConnection(
        local=config[DOMAIN].get(CONF_LOCAL_IP),
        localport=config[DOMAIN].get(CONF_LOCAL_PORT),
        remotes=remotes,
        systemcallback=bound_system_callback,
        interface_id='homeassistant'
    )

    # Start server thread, connect to hosts, initialize to receive events
    hass.data[DATA_HOMEMATIC].start()

    # Stops server when HASS is shutting down
    hass.bus.listen_once(
        EVENT_HOMEASSISTANT_STOP, hass.data[DATA_HOMEMATIC].stop)

    # Init homematic hubs
    entity_hubs = []
    for _, hub_data in hosts.items():
        entity_hubs.append(HMHub(
            hass, hub_data[CONF_NAME], hub_data[CONF_VARIABLES]))

    # Register HomeMatic services
    descriptions = load_yaml_config_file(
        os.path.join(os.path.dirname(__file__), 'services.yaml'))

    def _hm_service_virtualkey(service):
        """Service to handle virtualkey servicecalls."""
        address = service.data.get(ATTR_ADDRESS)
        channel = service.data.get(ATTR_CHANNEL)
        param = service.data.get(ATTR_PARAM)

        # Device not found
        hmdevice = _device_from_servicecall(hass, service)
        if hmdevice is None:
            _LOGGER.error("%s not found for service virtualkey!", address)
            return

        # Parameter doesn't exist for device
        if param not in hmdevice.ACTIONNODE:
            _LOGGER.error("%s not datapoint in hm device %s", param, address)
            return

        # Channel doesn't exist for device
        if channel not in hmdevice.ACTIONNODE[param]:
            _LOGGER.error("%i is not a channel in hm device %s",
                          channel, address)
            return

        # Call parameter
        hmdevice.actionNodeData(param, True, channel)

    hass.services.register(
        DOMAIN, SERVICE_VIRTUALKEY, _hm_service_virtualkey,
        descriptions[DOMAIN][SERVICE_VIRTUALKEY],
        schema=SCHEMA_SERVICE_VIRTUALKEY)

    def _service_handle_value(service):
        """Service to call setValue method for HomeMatic system variable."""
        entity_ids = service.data.get(ATTR_ENTITY_ID)
        name = service.data[ATTR_NAME]
        value = service.data[ATTR_VALUE]

        if entity_ids:
            entities = [entity for entity in entity_hubs if
                        entity.entity_id in entity_ids]
        else:
            entities = entity_hubs

        if not entities:
            _LOGGER.error("No HomeMatic hubs available")
            return

        for hub in entities:
            hub.hm_set_variable(name, value)

    hass.services.register(
        DOMAIN, SERVICE_SET_VAR_VALUE, _service_handle_value,
        descriptions[DOMAIN][SERVICE_SET_VAR_VALUE],
        schema=SCHEMA_SERVICE_SET_VAR_VALUE)

    def _service_handle_reconnect(service):
        """Service to reconnect all HomeMatic hubs."""
        hass.data[DATA_HOMEMATIC].reconnect()

    hass.services.register(
        DOMAIN, SERVICE_RECONNECT, _service_handle_reconnect,
        descriptions[DOMAIN][SERVICE_RECONNECT],
        schema=SCHEMA_SERVICE_RECONNECT)

    def _service_handle_device(service):
        """Service to call setValue method for HomeMatic devices."""
        address = service.data.get(ATTR_ADDRESS)
        channel = service.data.get(ATTR_CHANNEL)
        param = service.data.get(ATTR_PARAM)
        value = service.data.get(ATTR_VALUE)

        # Device not found
        hmdevice = _device_from_servicecall(hass, service)
        if hmdevice is None:
            _LOGGER.error("%s not found!", address)
            return

        hmdevice.setValue(param, value, channel)

    hass.services.register(
        DOMAIN, SERVICE_SET_DEV_VALUE, _service_handle_device,
        descriptions[DOMAIN][SERVICE_SET_DEV_VALUE],
        schema=SCHEMA_SERVICE_SET_DEV_VALUE)

    return True
Beispiel #6
0
def setup(hass, config):
    """Set up the Homematic component."""

    conf = config[DOMAIN]
    hass.data[DATA_CONF] = remotes = {}
    hass.data[DATA_STORE] = set()

    # Create hosts-dictionary for pyhomematic
    for rname, rconfig in conf[CONF_INTERFACES].items():
        remotes[rname] = {
            "ip": rconfig.get(CONF_HOST),
            "port": rconfig.get(CONF_PORT),
            "path": rconfig.get(CONF_PATH),
            "resolvenames": rconfig.get(CONF_RESOLVENAMES),
            "jsonport": rconfig.get(CONF_JSONPORT),
            "username": rconfig.get(CONF_USERNAME),
            "password": rconfig.get(CONF_PASSWORD),
            "callbackip": rconfig.get(CONF_CALLBACK_IP),
            "callbackport": rconfig.get(CONF_CALLBACK_PORT),
            "ssl": rconfig.get(CONF_SSL),
            "verify_ssl": rconfig.get(CONF_VERIFY_SSL),
            "connect": True,
        }

    for sname, sconfig in conf[CONF_HOSTS].items():
        remotes[sname] = {
            "ip": sconfig.get(CONF_HOST),
            "port": DEFAULT_PORT,
            "username": sconfig.get(CONF_USERNAME),
            "password": sconfig.get(CONF_PASSWORD),
            "connect": False,
        }

    # Create server thread
    bound_system_callback = partial(_system_callback_handler, hass, config)
    hass.data[DATA_HOMEMATIC] = homematic = HMConnection(
        local=config[DOMAIN].get(CONF_LOCAL_IP),
        localport=config[DOMAIN].get(CONF_LOCAL_PORT, DEFAULT_LOCAL_PORT),
        remotes=remotes,
        systemcallback=bound_system_callback,
        interface_id="homeassistant",
    )

    # Start server thread, connect to hosts, initialize to receive events
    homematic.start()

    # Stops server when HASS is shutting down
    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, hass.data[DATA_HOMEMATIC].stop)

    # Init homematic hubs
    entity_hubs = []
    for hub_name in conf[CONF_HOSTS].keys():
        entity_hubs.append(HMHub(hass, homematic, hub_name))

    def _hm_service_virtualkey(service):
        """Service to handle virtualkey servicecalls."""
        address = service.data.get(ATTR_ADDRESS)
        channel = service.data.get(ATTR_CHANNEL)
        param = service.data.get(ATTR_PARAM)

        # Device not found
        hmdevice = _device_from_servicecall(hass, service)
        if hmdevice is None:
            _LOGGER.error("%s not found for service virtualkey!", address)
            return

        # Parameter doesn't exist for device
        if param not in hmdevice.ACTIONNODE:
            _LOGGER.error("%s not datapoint in hm device %s", param, address)
            return

        # Channel doesn't exist for device
        if channel not in hmdevice.ACTIONNODE[param]:
            _LOGGER.error("%i is not a channel in hm device %s", channel, address)
            return

        # Call parameter
        hmdevice.actionNodeData(param, True, channel)

    hass.services.register(
        DOMAIN,
        SERVICE_VIRTUALKEY,
        _hm_service_virtualkey,
        schema=SCHEMA_SERVICE_VIRTUALKEY,
    )

    def _service_handle_value(service):
        """Service to call setValue method for HomeMatic system variable."""
        entity_ids = service.data.get(ATTR_ENTITY_ID)
        name = service.data[ATTR_NAME]
        value = service.data[ATTR_VALUE]

        if entity_ids:
            entities = [
                entity for entity in entity_hubs if entity.entity_id in entity_ids
            ]
        else:
            entities = entity_hubs

        if not entities:
            _LOGGER.error("No HomeMatic hubs available")
            return

        for hub in entities:
            hub.hm_set_variable(name, value)

    hass.services.register(
        DOMAIN,
        SERVICE_SET_VARIABLE_VALUE,
        _service_handle_value,
        schema=SCHEMA_SERVICE_SET_VARIABLE_VALUE,
    )

    def _service_handle_reconnect(service):
        """Service to reconnect all HomeMatic hubs."""
        homematic.reconnect()

    hass.services.register(
        DOMAIN,
        SERVICE_RECONNECT,
        _service_handle_reconnect,
        schema=SCHEMA_SERVICE_RECONNECT,
    )

    def _service_handle_device(service):
        """Service to call setValue method for HomeMatic devices."""
        address = service.data.get(ATTR_ADDRESS)
        channel = service.data.get(ATTR_CHANNEL)
        param = service.data.get(ATTR_PARAM)
        value = service.data.get(ATTR_VALUE)
        value_type = service.data.get(ATTR_VALUE_TYPE)

        # Convert value into correct XML-RPC Type.
        # https://docs.python.org/3/library/xmlrpc.client.html#xmlrpc.client.ServerProxy
        if value_type:
            if value_type == "int":
                value = int(value)
            elif value_type == "double":
                value = float(value)
            elif value_type == "boolean":
                value = bool(value)
            elif value_type == "dateTime.iso8601":
                value = datetime.strptime(value, "%Y%m%dT%H:%M:%S")
            else:
                # Default is 'string'
                value = str(value)

        # Device not found
        hmdevice = _device_from_servicecall(hass, service)
        if hmdevice is None:
            _LOGGER.error("%s not found!", address)
            return

        hmdevice.setValue(param, value, channel)

    hass.services.register(
        DOMAIN,
        SERVICE_SET_DEVICE_VALUE,
        _service_handle_device,
        schema=SCHEMA_SERVICE_SET_DEVICE_VALUE,
    )

    def _service_handle_install_mode(service):
        """Service to set interface into install mode."""
        interface = service.data.get(ATTR_INTERFACE)
        mode = service.data.get(ATTR_MODE)
        time = service.data.get(ATTR_TIME)
        address = service.data.get(ATTR_ADDRESS)

        homematic.setInstallMode(interface, t=time, mode=mode, address=address)

    hass.services.register(
        DOMAIN,
        SERVICE_SET_INSTALL_MODE,
        _service_handle_install_mode,
        schema=SCHEMA_SERVICE_SET_INSTALL_MODE,
    )

    def _service_put_paramset(service):
        """Service to call the putParamset method on a HomeMatic connection."""
        interface = service.data.get(ATTR_INTERFACE)
        address = service.data.get(ATTR_ADDRESS)
        paramset_key = service.data.get(ATTR_PARAMSET_KEY)
        # When passing in the paramset from a YAML file we get an OrderedDict
        # here instead of a dict, so add this explicit cast.
        # The service schema makes sure that this cast works.
        paramset = dict(service.data.get(ATTR_PARAMSET))

        _LOGGER.debug(
            "Calling putParamset: %s, %s, %s, %s",
            interface,
            address,
            paramset_key,
            paramset,
        )
        homematic.putParamset(interface, address, paramset_key, paramset)

    hass.services.register(
        DOMAIN,
        SERVICE_PUT_PARAMSET,
        _service_put_paramset,
        schema=SCHEMA_SERVICE_PUT_PARAMSET,
    )

    return True
def setup(hass, config):
    """Setup the Homematic component."""
    from pyhomematic import HMConnection

    component = EntityComponent(_LOGGER, DOMAIN, hass)

    hass.data[DATA_DELAY] = config[DOMAIN].get(CONF_DELAY)
    hass.data[DATA_DEVINIT] = {}
    hass.data[DATA_STORE] = []

    # create hosts list for pyhomematic
    remotes = {}
    hosts = {}
    for rname, rconfig in config[DOMAIN][CONF_HOSTS].items():
        server = rconfig.get(CONF_IP)

        remotes[rname] = {}
        remotes[rname][CONF_IP] = server
        remotes[rname][CONF_PORT] = rconfig.get(CONF_PORT)
        remotes[rname][CONF_RESOLVENAMES] = rconfig.get(CONF_RESOLVENAMES)
        remotes[rname][CONF_USERNAME] = rconfig.get(CONF_USERNAME)
        remotes[rname][CONF_PASSWORD] = rconfig.get(CONF_PASSWORD)

        if server not in hosts or rconfig.get(CONF_PRIMARY):
            hosts[server] = {
                CONF_VARIABLES: rconfig.get(CONF_VARIABLES),
                CONF_NAME: rname,
            }
        hass.data[DATA_DEVINIT][rname] = rconfig.get(CONF_DEVICES)

    # Create server thread
    bound_system_callback = partial(_system_callback_handler, hass, config)
    hass.data[DATA_HOMEMATIC] = HMConnection(
        local=config[DOMAIN].get(CONF_LOCAL_IP),
        localport=config[DOMAIN].get(CONF_LOCAL_PORT),
        remotes=remotes,
        systemcallback=bound_system_callback,
        interface_id="homeassistant")

    # Start server thread, connect to peer, initialize to receive events
    hass.data[DATA_HOMEMATIC].start()

    # Stops server when Homeassistant is shutting down
    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP,
                         hass.data[DATA_HOMEMATIC].stop)
    hass.config.components.append(DOMAIN)

    # init homematic hubs
    hub_entities = []
    for _, hub_data in hosts.items():
        hub_entities.append(
            HMHub(hass, component, hub_data[CONF_NAME],
                  hub_data[CONF_VARIABLES]))
    component.add_entities(hub_entities)

    # regeister homematic services
    descriptions = load_yaml_config_file(
        os.path.join(os.path.dirname(__file__), 'services.yaml'))

    def _hm_service_virtualkey(service):
        """Service handle virtualkey services."""
        address = service.data.get(ATTR_ADDRESS)
        channel = service.data.get(ATTR_CHANNEL)
        param = service.data.get(ATTR_PARAM)

        # device not found
        hmdevice = _device_from_servicecall(hass, service)
        if hmdevice is None:
            _LOGGER.error("%s not found for service virtualkey!", address)
            return

        # if param exists for this device
        if param not in hmdevice.ACTIONNODE:
            _LOGGER.error("%s not datapoint in hm device %s", param, address)
            return

        # channel exists?
        if channel not in hmdevice.ACTIONNODE[param]:
            _LOGGER.error("%i is not a channel in hm device %s", channel,
                          address)
            return

        # call key
        hmdevice.actionNodeData(param, True, channel)

    hass.services.register(DOMAIN,
                           SERVICE_VIRTUALKEY,
                           _hm_service_virtualkey,
                           descriptions[DOMAIN][SERVICE_VIRTUALKEY],
                           schema=SCHEMA_SERVICE_VIRTUALKEY)

    def _service_handle_value(service):
        """Set value on homematic variable object."""
        variable_list = component.extract_from_service(service)

        value = service.data[ATTR_VALUE]

        for hm_variable in variable_list:
            if isinstance(hm_variable, HMVariable):
                hm_variable.hm_set(value)

    hass.services.register(DOMAIN,
                           SERVICE_SET_VAR_VALUE,
                           _service_handle_value,
                           descriptions[DOMAIN][SERVICE_SET_VAR_VALUE],
                           schema=SCHEMA_SERVICE_SET_VAR_VALUE)

    def _service_handle_reconnect(service):
        """Reconnect to all homematic hubs."""
        hass.data[DATA_HOMEMATIC].reconnect()

    hass.services.register(DOMAIN,
                           SERVICE_RECONNECT,
                           _service_handle_reconnect,
                           descriptions[DOMAIN][SERVICE_RECONNECT],
                           schema=SCHEMA_SERVICE_RECONNECT)

    def _service_handle_device(service):
        """Service handle set_dev_value services."""
        address = service.data.get(ATTR_ADDRESS)
        channel = service.data.get(ATTR_CHANNEL)
        param = service.data.get(ATTR_PARAM)
        value = service.data.get(ATTR_VALUE)

        # device not found
        hmdevice = _device_from_servicecall(hass, service)
        if hmdevice is None:
            _LOGGER.error("%s not found!", address)
            return

        # call key
        hmdevice.setValue(param, value, channel)

    hass.services.register(DOMAIN,
                           SERVICE_SET_DEV_VALUE,
                           _service_handle_device,
                           descriptions[DOMAIN][SERVICE_SET_DEV_VALUE],
                           schema=SCHEMA_SERVICE_SET_DEV_VALUE)

    return True
Beispiel #8
0
    def __init__(self, sh, *args, **kwargs):
        """
        Initalizes the plugin. The parameters descriptions for this method are pulled from the entry in plugin.yaml.

        :param sh:  **Deprecated**: The instance of the smarthome object. For SmartHomeNG versions **beyond** 1.3: **Don't use it**! 
        :param *args: **Deprecated**: Old way of passing parameter values. For SmartHomeNG versions **beyond** 1.3: **Don't use it**!
        :param **kwargs:**Deprecated**: Old way of passing parameter values. For SmartHomeNG versions **beyond** 1.3: **Don't use it**!
        
        If you need the sh object at all, use the method self.get_sh() to get it. There should be almost no need for
        a reference to the sh object any more.
        
        The parameters *args and **kwargs are the old way of passing parameters. They are deprecated. They are imlemented
        to support older plugins. Plugins for SmartHomeNG v1.4 and beyond should use the new way of getting parameter values:
        use the SmartPlugin method get_parameter_value(parameter_name) instead. Anywhere within the Plugin you can get
        the configured (and checked) value for a parameter by calling self.get_parameter_value(parameter_name). It
        returns the value in the datatype that is defined in the metadata.
        """
        self.logger = logging.getLogger(__name__)

        # get the parameters for the plugin (as defined in metadata plugin.yaml):
        #   self.param1 = self.get_parameter_value('param1')
        
        # Initialization code goes here
        self.username = self.get_parameter_value('username')
        self.password = self.get_parameter_value('password')
        self.host = self.get_parameter_value('host')
#        self.port = self.get_parameter_value('port')
#        self.port_hmip = self.get_parameter_value('port_hmip')
        self.port = 2001
        self.port_hmip = 2010

        # build dict identifier for the homematic ccu of this plugin instance
        self.hm_id = 'rf'
        if self.get_instance_name() != '':
            self.hm_id += '_' + self.get_instance_name()
            self.log_instance_str = ' ('+self.get_instance_name()+')'
        else:
            self.log_instance_str = ''
        # create HomeMatic object
        try:
             self.hm = HMConnection(interface_id="myserver", autostart=False, 
                                    eventcallback=self.eventcallback, systemcallback=self.systemcallback, 
                                    remotes={self.hm_id:{"ip": self.host, "port": self.port}})
#                                    remotes={self.hm_id:{"ip": self.host, "port": self.port}, self.hmip_id:{"ip": self.host, "port": self.port_hmip}})
        except:
            self.logger.error("{}: Unable to create HomeMatic object".format(self.get_fullname()))
            self._init_complete = False
            return


        # build dict identifier for the homematicIP ccu of this plugin instance
        if self.port_hmip != 0:
            self.hmip_id = 'ip'
            if self.get_instance_name() != '':
                self.hmip_id += '_' + self.get_instance_name()
            # create HomeMaticIP object
            try:
                 self.hmip = HMConnection(interface_id="myserver_ip", autostart=False, 
                                          eventcallback=self.eventcallback, systemcallback=self.systemcallback, 
                                          remotes={self.hmip_id:{"ip": self.host, "port": self.port_hmip}})
            except:
                self.logger.error("{}: Unable to create HomeMaticIP object".format(self.get_fullname()))
#                self._init_complete = False
#                return


        # set the name of the thread that got created by pyhomematic to something meaningfull 
        self.hm._server.name = self.get_fullname()

        # start communication with HomeMatic ccu
        try:
            self.hm.start()
            self.connected = True
        except:
            self.logger.error("{}: Unable to start HomeMatic object - SmartHomeNG will be unable to terminate the thread vor this plugin (instance)".format(self.get_fullname()))
            self.connected = False
#            self._init_complete = False
            # stop the thread that got created by initializing pyhomematic 
#            self.hm.stop()
#            return

        # start communication with HomeMatic ccu
        try:
            self.hmip.start()
        except:
            self.logger.error("{}: Unable to start HomeMaticIP object".format(self.get_fullname()))

        if self.connected:
            # TO DO: sleep besser lösen!
            sleep(20)
#            self.logger.warning("Plugin '{}': self.hm.devices".format(self.hm.devices))
            if self.hm.devices.get(self.hm_id,{}) == {}:
                self.logger.error("{}: Connection to ccu failed".format(self.get_fullname()))
#                self._init_complete = False
                # stop the thread that got created by initializing pyhomematic 
#                self.hm.stop()
#                return
        
        self.hm_items = []           

        if not self.init_webinterface():
#            self._init_complete = False
            pass

        return
Beispiel #9
0
def setup(hass, config):
    """Setup the Homematic component."""
    global HOMEMATIC, HOMEMATIC_LINK_DELAY
    from pyhomematic import HMConnection

    component = EntityComponent(_LOGGER, DOMAIN, hass)

    local_ip = config[DOMAIN].get(CONF_LOCAL_IP)
    local_port = config[DOMAIN].get(CONF_LOCAL_PORT)
    remote_ip = config[DOMAIN].get(CONF_REMOTE_IP)
    remote_port = config[DOMAIN].get(CONF_REMOTE_PORT)
    resolvenames = config[DOMAIN].get(CONF_RESOLVENAMES)
    username = config[DOMAIN].get(CONF_USERNAME)
    password = config[DOMAIN].get(CONF_PASSWORD)
    HOMEMATIC_LINK_DELAY = config[DOMAIN].get(CONF_DELAY)
    use_variables = config[DOMAIN].get(CONF_VARIABLES)

    if remote_ip is None or local_ip is None:
        _LOGGER.error("Missing remote CCU/Homegear or local address")
        return False

    # Create server thread
    bound_system_callback = partial(_system_callback_handler, hass, config)
    HOMEMATIC = HMConnection(local=local_ip,
                             localport=local_port,
                             remote=remote_ip,
                             remoteport=remote_port,
                             systemcallback=bound_system_callback,
                             resolvenames=resolvenames,
                             rpcusername=username,
                             rpcpassword=password,
                             interface_id="homeassistant")

    # Start server thread, connect to peer, initialize to receive events
    HOMEMATIC.start()

    # Stops server when Homeassistant is shutting down
    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, HOMEMATIC.stop)
    hass.config.components.append(DOMAIN)

    # regeister homematic services
    descriptions = load_yaml_config_file(
        os.path.join(os.path.dirname(__file__), 'services.yaml'))

    hass.services.register(DOMAIN,
                           SERVICE_VIRTUALKEY,
                           _hm_service_virtualkey,
                           descriptions[DOMAIN][SERVICE_VIRTUALKEY],
                           schema=SCHEMA_SERVICE_VIRTUALKEY)

    entities = []

    ##
    # init HM variable
    variables = HOMEMATIC.getAllSystemVariables() if use_variables else {}
    hm_var_store = {}
    if variables is not None:
        for key, value in variables.items():
            varia = HMVariable(key, value)
            hm_var_store.update({key: varia})
            entities.append(varia)

    # add homematic entites
    entities.append(HMHub(hm_var_store, use_variables))
    component.add_entities(entities)

    ##
    # register set_value service if exists variables
    if not variables:
        return True

    def _service_handle_value(service):
        """Set value on homematic variable object."""
        variable_list = component.extract_from_service(service)

        value = service.data[ATTR_VALUE]

        for hm_variable in variable_list:
            hm_variable.hm_set(value)

    hass.services.register(DOMAIN,
                           SERVICE_SET_VALUE,
                           _service_handle_value,
                           descriptions[DOMAIN][SERVICE_SET_VALUE],
                           schema=SCHEMA_SERVICE_SET_VALUE)

    return True
Beispiel #10
0
DEVICE2 = 'address_of_doorcontact'  # e.g. LEQ1234567
DEVICE3 = 'address_of_thermostat'

def systemcallback(src, *args):
    print(src)
    for arg in args:
        print(arg)

try:
    # Create a server that listens on 127.0.0.1:7080 and identifies itself as myserver.
    # Connect to Homegear at 127.0.0.1:2001
    # Automatically start everything. Without autostart, pyhomematic.start() can be called.
    # We add a systemcallback so we can see what else happens besides the regular events.
    pyhomematic = HMConnection(interface_id="myserver",
                               autostart=True,
                               systemcallback=systemcallback,
                               remotes={"rf":{
                                   "ip":"127.0.0.1",
                                   "port": 2001}})
except Exception:
    sys.exit(1)

sleepcounter = 0

def eventcallback(address, interface_id, key, value):
    print("CALLBACK: %s, %s, %s, %s" % (address, interface_id, key, value))

while not pyhomematic.devices and sleepcounter < 20:
    print("Waiting for devices")
    sleepcounter += 1
    time.sleep(1)
print(pyhomematic.devices)
Beispiel #11
0
    def __init__(self, sh, *args, **kwargs):
        """
        Initalizes the plugin.

        If you need the sh object at all, use the method self.get_sh() to get it. There should be almost no need for
        a reference to the sh object any more.

        Plugins have to use the new way of getting parameter values:
        use the SmartPlugin method get_parameter_value(parameter_name). Anywhere within the Plugin you can get
        the configured (and checked) value for a parameter by calling self.get_parameter_value(parameter_name). It
        returns the value in the datatype that is defined in the metadata.
        """

        # Call init code of parent class (SmartPlugin)
        super().__init__()

        # get the parameters for the plugin (as defined in metadata plugin.yaml):
        #   self.param1 = self.get_parameter_value('param1')

        # Initialization code goes here
        self.username = self.get_parameter_value('username')
        self.password = self.get_parameter_value('password')
        self.host = self.get_parameter_value('host')
        #        self.port = self.get_parameter_value('port')
        #        self.port_hmip = self.get_parameter_value('port_hmip')
        self.port = 2001
        self.port_hmip = 2010

        # build dict identifier for the homematic ccu of this plugin instance
        self.hm_id = 'rf'
        if self.get_instance_name() != '':
            self.hm_id += '_' + self.get_instance_name()
        # create HomeMatic object
        try:
            self.hm = HMConnection(
                interface_id="myserver",
                autostart=False,
                eventcallback=self.eventcallback,
                systemcallback=self.systemcallback,
                remotes={self.hm_id: {
                    "ip": self.host,
                    "port": self.port
                }})
#                                    remotes={self.hm_id:{"ip": self.host, "port": self.port}, self.hmip_id:{"ip": self.host, "port": self.port_hmip}})
        except:
            self.logger.error("Unable to create HomeMatic object")
            self._init_complete = False
            return

        # build dict identifier for the homematicIP ccu of this plugin instance
        if self.port_hmip != 0:
            self.hmip_id = 'ip'
            if self.get_instance_name() != '':
                self.hmip_id += '_' + self.get_instance_name()
            # create HomeMaticIP object
            try:
                self.hmip = HMConnection(interface_id="myserver_ip",
                                         autostart=False,
                                         eventcallback=self.eventcallback,
                                         systemcallback=self.systemcallback,
                                         remotes={
                                             self.hmip_id: {
                                                 "ip": self.host,
                                                 "port": self.port_hmip
                                             }
                                         })
            except:
                self.logger.error("Unable to create HomeMaticIP object")
#                self._init_complete = False
#                return

# set the name of the thread that got created by pyhomematic to something meaningfull
        self.hm._server.name = 'plugins.' + self.get_fullname() + '.server'

        # start communication with HomeMatic ccu
        try:
            self.hm.start()
            self.connected = True
        except:
            self.logger.error(
                "Unable to start HomeMatic object - SmartHomeNG will be unable to terminate the thread vor this plugin (instance)"
            )
            self.connected = False
        #            self._init_complete = False
        # stop the thread that got created by initializing pyhomematic
        #            self.hm.stop()
        #            return

        # start communication with HomeMatic ccu
        try:
            self.hmip.start()
        except:
            self.logger.error("{}: Unable to start HomeMaticIP object".format(
                self.get_fullname()))

        if self.connected:
            # TO DO: sleep besser lösen!
            sleep(20)
            #            self.logger.warning("Plugin '{}': self.hm.devices".format(self.hm.devices))
            if self.hm.devices.get(self.hm_id, {}) == {}:
                self.logger.error("Connection to ccu failed")
        #                self._init_complete = False
        # stop the thread that got created by initializing pyhomematic
        #                self.hm.stop()
        #                return

        self.hm_items = []

        self.init_webinterface(WebInterface)

        return