fauxmo.plugins package

Submodules

fauxmo.plugins.commandlineplugin module

Fauxmo plugin that runs a command on the local machine.

Runs a shlex`ed command using `subprocess.run, keeping the default of shell=False. This is probaby frought with security concerns, which is why this plugin is not included by default in fauxmo.plugins. By installing or using it, you acknowledge that it could run commands from your config.json that could lead to data compromise, corruption, loss, etc. Consider making your config.json read-only. If there are parts of this you don’t understand, you should probably not use this plugin.

If the command runs with a return code of 0, Alexa should respond prompty “Okay” or something that indicates it seems to have worked. If the command has a return code of anything other than 0, Alexa stalls for several seconds and subsequently reports that there was a problem (which should notify the user that something didn’t go as planned).

Note that subprocess.run as implemented in this plugin doesn’t handle complex commands with pipes, redirection, or multiple statements joined by &&, ||, ;, etc., so you can’t just use e.g. “command that sometimes fails || true” to avoid the delay and Alexa’s response. If you really want to handle more complex commands, consider using this plugin as a template for another one using os.system instead of subprocess.run, but realize that this comes with substantial security risks that exceed my ability to explain.

Example config: ``` {

“FAUXMO”: {
“ip_address”: “auto”

}, “PLUGINS”: {

“CommandLinePlugin”: {

“path”: “/path/to/commandlineplugin.py”, “DEVICES”: [

{
“name”: “output stuff to a file”, “port”: 49915, “on_cmd”: “touch testfile.txt”, “off_cmd”: “rm testfile.txt”, “state_cmd”: “ls testfile.txt”

}, {

“name”: “command with fake state”, “port”: 49916, “on_cmd”: “touch testfile.txt”, “off_cmd”: “rm testfile.txt”, “use_fake_state”: true

}

]

}

}

}

class fauxmo.plugins.commandlineplugin.CommandLinePlugin(name: str, port: int, on_cmd: str, off_cmd: str, state_cmd: str = None, use_fake_state: bool = False)[source]

Bases: fauxmo.plugins.FauxmoPlugin

Fauxmo Plugin for running commands on the local machine.

__init__(name: str, port: int, on_cmd: str, off_cmd: str, state_cmd: str = None, use_fake_state: bool = False) → None[source]

Initialize a CommandLinePlugin instance.

Parameters:
  • 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
  • off_cmd – Command to be called when turning device off
  • state_cmd – Command to check device state (return code 0 == on)
  • use_fake_state – If True, override get_state to return the latest action as the device state. NB: The proper json boolean value for Python’s True is true, not True or “true”.
get_state() → str[source]

Get device state.

NB: Return code of 0 (i.e. ran without error) indicates “on” state, otherwise will be off. making it easier to have something like ls path/to/pidfile suggest on. Many command line switches may not actually have a “state” per se (just an arbitary command you want to run), in which case you could just put “false” as the command, which should always return “off”.

Returns:“on” or “off” if state_cmd is defined, “unknown” if undefined
off() → bool[source]

Run off command.

Returns:True if command seems to have run without error.
on() → bool[source]

Run on command.

Returns:True if command seems to have run without error.
run_cmd(cmd: str) → bool[source]

Partialmethod to run command.

Parameters:cmd – Command to be run
Returns:True if command seems to have run without error

fauxmo.plugins.homeassistantplugin module

Fauxmo plugin to interact with Home Assistant devices.

One simple way to find your entity_id is to use curl and pipe to grep or jq. Note that modern versions of home-assistant require you to create and include a long-lived access token, which you can generate in the web interface at the /profile endpoint.

curl –silent –header “Authorization: Bearer YourTokenHere” http://IP:PORT/api/states | jq

NB: This is just a special case of the RESTAPIPlugin (or even SimpleHTTPPlugin, see config-sample.json in the main Fauxmo repo), but it makes config substantially easier by not having to redundantly specify headers and endpoints.

Install to Fauxmo by downloading or cloning and including in your Fauxmo config. One easy way to make a long-lived access token is by using the frontend and going to the /profile endpoint, scroll to the bottom. Documentation on the long-lived tokens is available at https://developers.home-assistant.io/docs/en/auth_api.html#long-lived-access-token

Example config: ``` {

“FAUXMO”: {
“ip_address”: “auto”

}, “PLUGINS”: {

“HomeAssistantPlugin”: {

“ha_host”: “192.168.0.50”, “ha_port”: 8123, “ha_protocol”: “http”, “ha_token”: “abc123”, “path”: “/path/to/homeassistantplugin.py”, “DEVICES”: [

{
“name”: “example Home Assistant device 1”, “port”: 12345, “entity_id”: “switch.my_fake_switch”

}, {

“name”: “example Home Assistant device 2”, “port”: 12346, “entity_id”: “cover.my_fake_cover”

}

]

}

}

}

class fauxmo.plugins.homeassistantplugin.HomeAssistantPlugin(name: str, port: int, entity_id: str, ha_host: str, ha_port: int = 8123, ha_protocol: str = 'http', ha_token: str = None)[source]

Bases: fauxmo.plugins.FauxmoPlugin

Fauxmo plugin for HomeAssistant REST API.

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

__init__(name: str, port: int, entity_id: str, ha_host: str, ha_port: int = 8123, ha_protocol: str = 'http', ha_token: str = None) → None[source]

Initialize a HomeAssistantPlugin instance.

Parameters:
  • ha_token – Long-lived HomeAssistant token
  • entity_identity_id used by HomeAssistant
  • ha_host – Host running HomeAssistant
  • ha_port – Port number for HomeAssistant access
  • ha_protocol – http or https
get_state() → str[source]

Query the state of the Home Assistant device.

Returns: Device state as reported by HomeAssistant

off() → bool[source]

Turn the Home Assistant device off.

Returns: Whether the device seems to have been turned off.

on() → bool[source]

Turn the Home Assistant device on.

Returns: Whether the device seems to have been turned on.

send(signal: str) → bool[source]

Send signal as determined by service_map.

Parameters:signal – the signal the service should recongize
service_map = {'cover': {'off': 'close_cover', 'off_state': 'closed', 'on': 'open_cover', 'on_state': 'open'}, 'homeassistant': {'off': 'turn_off', 'on': 'turn_on'}, 'light': {'off': 'turn_off', 'on': 'turn_on'}, 'media_player': {'off': 'turn_off', 'on': 'turn_on'}, 'switch': {'off': 'turn_off', 'on': 'turn_on'}}

fauxmo.plugins.simplehttpplugin module

simplehttpplugin.py :: Fauxmo plugin for simple HTTP requests.

Fauxmo plugin that makes simple HTTP requests in its on and off methods. Comes pre-installed in Fauxmo as an example for user plugins.

For more complicated requests (e.g. authentication, sending JSON), check out RESTAPIPlugin in https://github.com/n8henrie/fauxmo-plugins/, which takes advantage of Requests’ rich API.

class fauxmo.plugins.simplehttpplugin.SimpleHTTPPlugin(*, headers: dict = None, method: str = 'GET', name: str, off_cmd: str, off_data: Union[Mapping[KT, VT_co], str] = None, on_cmd: str, on_data: Union[Mapping[KT, VT_co], str] = None, state_cmd: str = None, state_data: Union[Mapping[KT, VT_co], str] = None, state_method: str = 'GET', state_response_off: str = None, state_response_on: str = None, password: str = None, port: int, use_fake_state: bool = False, user: str = None)[source]

Bases: fauxmo.plugins.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 request to localhost:8765/state with <p>Device is running</p> or <p>Device is not running</p>, you could use those strings as state_command_on and state_command_off, respectively.

__init__(*, headers: dict = None, method: str = 'GET', name: str, off_cmd: str, off_data: Union[Mapping[KT, VT_co], str] = None, on_cmd: str, on_data: Union[Mapping[KT, VT_co], str] = None, state_cmd: str = None, state_data: Union[Mapping[KT, VT_co], str] = None, state_method: str = 'GET', state_response_off: str = None, state_response_on: str = None, password: str = None, port: int, use_fake_state: bool = False, user: str = None) → None[source]

Initialize a SimpleHTTPPlugin instance.

Keyword Arguments:
 
  • headers – Additional headers for both on() and off()
  • method – HTTP method to be used for both on() and off()
  • name – Name of the device
  • off_cmd – URL to be called when turning device off
  • off_data – Optional POST data to turn device off
  • on_cmd – URL to be called when turning device on
  • on_data – Optional POST data to turn device on
  • state_cmd – URL to be called to determine device state
  • state_data – Optional POST data to query device state
  • state_method – HTTP method to be used for get_state()
  • state_response_off – If this string is in the response to state_cmd, the device is off.
  • password – Password for HTTP authentication (basic or digest only)
  • port – Port that this device will run on
  • use_fake_state – If True, override get_state to return the latest action as the device state. NB: The proper json boolean value for Python’s True is true, not True or “true”.
  • user – Username for HTTP authentication (basic or digest only)
get_state() → str[source]

Get device state.

Returns:“on”, “off”, or “unknown”
off() → bool[source]

Turn device off by calling self.off_cmd with self.off_data.

Returns:True if the request seems to have been sent successfully
on() → bool[source]

Turn device on by calling self.on_cmd with self.on_data.

Returns:True if the request seems to have been sent successfully
set_state(cmd: str, data: bytes) → bool[source]

Call HTTP method, for use by functools.partialmethod.

Parameters:
  • cmd – Either “on_cmd” or “off_cmd”, for getattr(self, cmd)
  • data – Either “on_data” or “off_data”, for getattr(self, data)
Returns:

Boolean indicating whether it state was set successfully

Module contents

fauxmo.plugins :: Provide ABC for Fauxmo plugins.

class fauxmo.plugins.FauxmoPlugin(*, name: str, port: int)[source]

Bases: abc.ABC

Provide ABC for Fauxmo plugins.

This will become the plugin attribute of a Fauxmo instance. Its on and off methods will be called when Alexa turns something on or off.

All keys (other than the list of DEVICES) from the config will be passed into FauxmoPlugin as kwargs at initialization, which should let users do some interesting things. However, that means users employing custom config keys will need to override __init__ and either set the name and “private” _port attributes manually or pass the appropriate args to super().__init__().

__init__(*, name: str, port: int) → None[source]

Initialize FauxmoPlugin.

Keyword Arguments:
 
  • name – Required, device name
  • port – Required, port that the Fauxmo associated with this plugin should run on

Note about port: if not given in config, it will be set to an apparently free port in fauxmo.fauxmo before FauxmoPlugin initialization. This attribute serves no default purpose in the FauxmoPlugin but is passed in to be accessible by user code (i.e. for logging / debugging). Alternatively, one could accept and throw away the passed in port value and generate their own port in a plugin, since the Fauxmo device determines its port from the plugin’s instance attribute.

The _latest_action attribute stores the most recent successful action, which is set by the __getattribute__ hackery for successful .on() and .off() commands.

close() → None[source]

Run when shutting down; allows plugin to clean up state.

get_state() → str[source]

Run function when Alexa requests device state.

Should return “on” or “off” if it can be determined, or “unknown” if there is no mechanism for determining the device state, in which case Alexa will complain that the device is not responding.

If state cannot be determined, a plugin can opt into this implementation, which falls back on the _latest_action attribute. It is intentionally left as an abstract method so that plugins cannot omit a get_state method completely, which could lead to unexpected behavior; instead, they should explicitly return super().get_state().

latest_action

Return latest action in read-only manner.

Must be a function instead of e.g. property because it overrides get_state, and therefore must be callable.

name

Return name attribute in read-only manner.

off() → bool[source]

Run function when Alexa turns this Fauxmo device off.

on() → bool[source]

Run function when Alexa turns this Fauxmo device on.

port

Return port attribute in read-only manner.