How to use the fauxmo.plugins.FauxmoPlugin function in fauxmo

To help you get started, we’ve selected a few fauxmo examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github n8henrie / fauxmo / src / fauxmo / fauxmo.py View on Github external
)
        print(errmsg)
        sys.exit(1)

    for plugin in plugins:

        modname = f"{__package__}.plugins.{plugin.lower()}"
        try:
            module = importlib.import_module(modname)

        except ModuleNotFoundError:
            path_str = config["PLUGINS"][plugin]["path"]
            module = module_from_file(modname, path_str)

        PluginClass = getattr(module, plugin)  # noqa
        if not issubclass(PluginClass, FauxmoPlugin):
            raise TypeError(f"Plugins must inherit from {repr(FauxmoPlugin)}")

        # Pass along variables defined at the plugin level that don't change
        # per device
        plugin_vars = {
            k: v
            for k, v in config["PLUGINS"][plugin].items()
            if k not in {"DEVICES", "path"}
        }
        logger.debug(f"plugin_vars: {repr(plugin_vars)}")

        for device in config["PLUGINS"][plugin]["DEVICES"]:
            logger.debug(f"device config: {repr(device)}")

            # Ensure port is `int`, set it if not given (`None`) or 0
            device["port"] = int(device.get("port", 0)) or get_unused_port()
github n8henrie / fauxmo-plugins / mqttplugin.py View on Github external
}
    }
}

Dependencies: paho-mqtt==1.3.1 """

from typing import List, Sequence

from fauxmo.plugins import FauxmoPlugin from paho.mqtt.client import Client, MQTTMessage

class MQTTPlugin(FauxmoPlugin): """Fauxmo plugin to interact with an MQTT server by way of paho."""

def __init__(
    self,
    *,
    name: str,
    port: int,
    off_cmd: Sequence[str],
    on_cmd: Sequence[str],
    mqtt_port: int = 1883,
    mqtt_pw: str = None,
    mqtt_user: str = None,
    mqtt_server: str = "127.0.0.1",
    state_cmd: str = None,
) -> None:
    """Initialize an MQTTPlugin instance.
github n8henrie / fauxmo-plugins / zwaveplugin.py View on Github external

Dependencies: requests==2.18.4 """

import requests from fauxmo import logger from fauxmo.plugins import FauxmoPlugin

ZwavePlugin_version = "v0.3"

response_ok = '{"data":null,"code":200,"message":"200 OK","error":null}'

class ZwavePlugin(FauxmoPlugin): """Fauxmo Plugin for Z-WAVE (zway-server) REST API.

Allows users to specify Z-Wave services in their config.json and
toggle these with the Echo. While this can be done with Z-Wave
REST API as well (example included), I find it easier to use the Python
API.

"""

def __init__(
    self,
    *,
    name: str,
    port: int,
    device: str,
    zwave_host: str = "localhost",
github n8henrie / fauxmo-plugins / homeassistantplugin.py View on Github external
]
        }
    }
}

"""

import json import urllib.parse import urllib.request from http.client import HTTPResponse

from fauxmo.plugins import FauxmoPlugin

class HomeAssistantPlugin(FauxmoPlugin): """Fauxmo plugin for HomeAssistant REST API.

Allows users to specify Home Assistant services in their config.json and
toggle these with the Echo.
"""

service_map = {
    "cover": {
        "on": "open_cover",
        "off": "close_cover",
        "on_state": "open",
        "off_state": "closed",
    },
    "homeassistant": {"on": "turn_on", "off": "turn_off"},
    "light": {"on": "turn_on", "off": "turn_off"},
    "media_player": {"on": "turn_on", "off": "turn_off"},
github n8henrie / fauxmo / src / fauxmo / plugins / simplehttpplugin.py View on Github external
RESTAPIPlugin in `https://github.com/n8henrie/fauxmo-plugins/`, which takes
advantage of Requests' rich API.
"""

import http
import urllib.parse
import urllib.request
from http.cookiejar import CookieJar
from typing import Mapping, Union
from urllib.error import HTTPError

from fauxmo import logger
from fauxmo.plugins import FauxmoPlugin


class SimpleHTTPPlugin(FauxmoPlugin):
    """Plugin for interacting with HTTP devices.

    The Fauxmo class expects plguins to be instances of objects that inherit
    from FauxmoPlugin and have on() and off() methods that return True on
    success and False otherwise. This class takes a mix of url, method, header,
    body, and auth data and makes REST calls to a device.

    This is probably less flexible than using Requests but doesn't add any
    non-stdlib dependencies. For an example using Requests, see the
    fauxmo-plugins repo.

    The implementation of the `get_state()` method is admittedly sloppy, trying
    to be somewhat generic to cover a broad range of devices that may have
    a state that can be queried by either GET or POST request (sometimes
    differing from the method required to turn on or off), and whose response
    often contains the state. For example, if state is returned by a GET
github n8henrie / fauxmo-plugins / hassapiplugin.py View on Github external
"""

from collections import defaultdict
from typing import Dict

import homeassistant.remote
from fauxmo.plugins import FauxmoPlugin
from homeassistant.const import (  # noqa
        SERVICE_TURN_ON, SERVICE_TURN_OFF,
        SERVICE_OPEN_COVER, SERVICE_CLOSE_COVER,
        STATE_OFF, STATE_ON,
        STATE_CLOSED, STATE_OPEN,
        )


class HassAPIPlugin(FauxmoPlugin):
    """Fauxmo Plugin for HomeAssistant (hass) Python API.

    Allows users to specify Home Assistant services in their config.json and
    toggle these with the Echo. While this can be done with Home Assistant's
    REST API as well (example included), I find it easier to use the Python
    API.
    """

    service_map: Dict[str, Dict[str, str]] = defaultdict(dict)
    service_map.update({
            'cover': {
                'on': SERVICE_OPEN_COVER,
                'off': SERVICE_CLOSE_COVER,
                'on_state': STATE_OPEN,
                'off_state': STATE_CLOSED,
                },
github n8henrie / fauxmo / src / fauxmo / plugins / commandlineplugin.py View on Github external
"use_fake_state": true
        }
      ]
    }
  }
}

"""

import shlex import subprocess

from fauxmo.plugins import FauxmoPlugin

class CommandLinePlugin(FauxmoPlugin): """Fauxmo Plugin for running commands on the local machine."""

def __init__(
    self,
    name: str,
    port: int,
    on_cmd: str,
    off_cmd: str,
    state_cmd: str = None,
    use_fake_state: bool = False,
) -> None:
    """Initialize a CommandLinePlugin instance.

    Args:
        name: Name for this Fauxmo device
        port: Port on which to run a specific CommandLinePlugin instance
github n8henrie / fauxmo-plugins / restapiplugin.py View on Github external
}
}

Dependencies: requests==2.18.4 """

import requests from requests.auth import HTTPBasicAuth, HTTPDigestAuth from typing import Union # noqa

from fauxmo.plugins import FauxmoPlugin

class RESTAPIPlugin(FauxmoPlugin): """REST API plugin class.

The Fauxmo class expects plugins to be instances of objects that have on()
and off() methods that return True on success and False otherwise. This
class takes a mix of url, method, header, body, and auth data and makes
REST calls to a device.
"""

def __init__(
    self,
    *,
    auth_type: str = None,
    headers: dict = None,
    method: str = "GET",
    name: str,
    off_cmd: str,
github n8henrie / fauxmo / src / fauxmo / plugins / homeassistantplugin.py View on Github external
]
        }
    }
}

"""

import json import urllib.parse import urllib.request from http.client import HTTPResponse

from fauxmo.plugins import FauxmoPlugin

class HomeAssistantPlugin(FauxmoPlugin): """Fauxmo plugin for HomeAssistant REST API.

Allows users to specify Home Assistant services in their config.json and
toggle these with the Echo.
"""

service_map = {
    "cover": {
        "on": "open_cover",
        "off": "close_cover",
        "on_state": "open",
        "off_state": "closed",
    },
    "homeassistant": {"on": "turn_on", "off": "turn_off"},
    "light": {"on": "turn_on", "off": "turn_off"},
    "media_player": {"on": "turn_on", "off": "turn_off"},
github n8henrie / fauxmo-plugins / commandlineplugin.py View on Github external
"state_cmd": "ls testfile.txt",
        }
      ]
    }
  }
}

"""

import shlex import subprocess

from fauxmo.plugins import FauxmoPlugin

class CommandLinePlugin(FauxmoPlugin): """Fauxmo Plugin for running commands on the local machine."""

def __init__(
    self,
    name: str,
    port: int,
    on_cmd: str,
    off_cmd: str,
    state_cmd: str = None,
) -> None:
    """Initialize a CommandLinePlugin instance.

    Args:
        name: Name for this Fauxmo device
        port: Port on which to run a specific CommandLinePlugin instance
        on_cmd: Command to be called when turning device on