61 lines
1.8 KiB
Python
61 lines
1.8 KiB
Python
from datetime import datetime
|
|
import logging
|
|
import psutil
|
|
import subprocess
|
|
|
|
from ha_mqtt_discoverable import Settings
|
|
from ha_mqtt_discoverable.sensors import Button, ButtonInfo
|
|
from paho.mqtt.client import Client, MQTTMessage
|
|
|
|
from ha_mqtt_agent.device import Device
|
|
from ha_mqtt_agent.util import EntityUtils
|
|
|
|
|
|
class BaseButton:
|
|
_name: str
|
|
_icon: str
|
|
_mqtt_button: Button
|
|
|
|
def __init__(self, name: str, icon: str):
|
|
self._name = name
|
|
self._icon = icon
|
|
|
|
def setup(self, device: Device):
|
|
button_info = ButtonInfo(
|
|
name=self._name,
|
|
device=device.mqtt_device,
|
|
unique_id=EntityUtils.unique_id(self._name, device),
|
|
icon=self._icon,
|
|
)
|
|
button_settings = Settings(mqtt=device.mqtt_settings, entity=button_info)
|
|
self._mqtt_button = Button(button_settings, self.callback)
|
|
self._mqtt_button.write_config()
|
|
|
|
def callback(self, client: Client, user_data, message: MQTTMessage):
|
|
logging.warning("no callback defined")
|
|
|
|
|
|
class ShellCommandButton(BaseButton):
|
|
_cmd: str
|
|
|
|
def __init__(self, name: str, cmd: str, icon: str = "mdi:button-pointer"):
|
|
super().__init__(name=name, icon=icon)
|
|
self._cmd = cmd
|
|
|
|
def callback(self, client: Client, user_data, message: MQTTMessage):
|
|
logging.info(f'running command "{ self._cmd }"')
|
|
subprocess.run(["sh", "-c", self._cmd])
|
|
|
|
|
|
class SystemctlRebootButton(ShellCommandButton):
|
|
def __init__(self):
|
|
super().__init__(
|
|
name="Reboot", cmd="sudo systemctl reboot", icon="mdi:autorenew"
|
|
)
|
|
|
|
|
|
class SystemctlShutdownButton(ShellCommandButton):
|
|
def __init__(self):
|
|
super().__init__(
|
|
name="Shutdown", cmd="sudo systemctl poweroff", icon="mdi:power"
|
|
)
|