|
import json |
|
import requests |
|
|
|
from fauxmo import logger |
|
from fauxmo.plugins import FauxmoPlugin |
|
|
|
|
|
class ReefPiMacroPlugin(FauxmoPlugin): |
|
"""Plugin for interacting with ReefPi macros |
|
""" |
|
|
|
def __init__( |
|
self, |
|
*, |
|
host: str, |
|
username: str, |
|
password: str, |
|
macroname: str, |
|
name: str, |
|
port: int |
|
) -> None: |
|
"""Initialize a ReefPiMacroPlugin |
|
""" |
|
self.host = host |
|
self.username = username |
|
self.password = password |
|
self.macroname = macroname |
|
|
|
super().__init__(name=name, port=port) |
|
|
|
def set_state(self, cmd: str, data: bytes) -> bool: |
|
session = requests.Session(); |
|
session.post("http://{host}/auth/signin".format(host = self.host), data = json.dumps({"user":self.username,"password":self.password})) |
|
r = session.get("http://{host}/api/macros".format(host = self.host)) |
|
macros = json.loads(r.text) |
|
macro = [m for m in macros if m['name'] == self.macroname][0] |
|
logger.info(macro) |
|
if cmd and not macro['enable']: |
|
r = session.post("http://{host}/api/macros/{id}/run".format(id=macro['id'], host = self.host)) |
|
return True |
|
|
|
def on(self) -> bool: |
|
"""Turn device on by calling `self.on_cmd` with `self.on_data`. |
|
Returns: |
|
True if the request seems to have been sent successfully |
|
""" |
|
return self.set_state(True, None) |
|
|
|
def off(self) -> bool: |
|
"""Turn device off by calling `self.off_cmd` with `self.off_data`. |
|
Returns: |
|
True if the request seems to have been sent successfully |
|
""" |
|
return self.set_state(False, None) |
|
|
|
def get_state(self) -> str: |
|
"""Get device state. |
|
Returns: |
|
"on", "off", or "unknown" |
|
""" |
|
session = requests.Session(); |
|
session.post("http://{host}/auth/signin".format(host = self.host), data = json.dumps({"user":self.username,"password":self.password})) |
|
r = session.get("http://{host}/api/macros".format(host = self.host)) |
|
macros = json.loads(r.text) |
|
macro = [m for m in macros if m['name'] == self.macroname][0] |
|
logger.info(macro) |
|
if not macro['enable']: |
|
return "off" |
|
else: |
|
return "on" |