Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

power: make the plugin more modular #35

Merged
merged 1 commit into from
Nov 9, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 36 additions & 28 deletions moonraker/plugins/power.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,23 +34,15 @@ def __init__(self, config):
logging.info("Power plugin loading devices: " + str(dev_names))
devices = {}
for dev in dev_names:
pin = config.getint(dev + "_pin")
name = config.get(dev + "_name", dev)
active_low = config.getboolean(dev + "_active_low", False)
devices[dev] = {
"name": name,
"pin": pin,
"active_low": int(active_low),
"status": None
}
devices[dev] = GpioDevice(dev, config)
ioloop = IOLoop.current()
ioloop.spawn_callback(self.initialize_devices, devices)

async def _handle_list_devices(self, path, method, args):
output = {"devices": []}
for dev in self.devices:
output['devices'].append({
"name": self.devices[dev]["name"],
"name": self.devices[dev].name,
"id": dev
})
return output
Expand All @@ -65,43 +57,35 @@ async def _handle_power_request(self, path, method, args):
result = {}
req = path.split("/")[-1]
for dev in args:
if path.startswith("/machine/gpio_power/"):
res = await self._power_dev(dev, req)
if res:
result[dev] = self.devices[dev]["status"]
else:
result[dev] = "device_not_found"
else:
if req not in ("on", "off", "status"):
raise self.server.error("Unsupported power request")
if (await self._power_dev(dev, req)):
result[dev] = self.devices[dev].status
else:
result[dev] = "device_not_found"
return result

async def _power_dev(self, dev, req):
if dev not in self.devices:
return False

await GPIO.verify_pin(self.devices[dev]["pin"],
self.devices[dev]["active_low"])
if req in ["on", "off"]:
val = 1 if req == "on" else 0
GPIO.set_pin_value(self.devices[dev]["pin"], val)
await self.devices[dev].power(req)

self.server.send_event("gpio_power:power_changed", {
"device": dev,
"status": req
})
elif req != "status":
raise self.server.error("Unsupported power request")

self.devices[dev]["status"] = GPIO.is_pin_on(
self.devices[dev]["pin"])
await self.devices[dev].refresh_status()
return True

async def initialize_devices(self, devices):
for name, device in devices.items():
try:
logging.debug(
f"Attempting to configure pin GPIO{device['pin']}")
await GPIO.setup_pin(device["pin"], device["active_low"])
device["status"] = GPIO.is_pin_on(device["pin"])
await device.initialize()
except Exception:
logging.exception(
f"Power plugin: ERR Problem configuring the output pin for"
Expand All @@ -123,6 +107,11 @@ def set_device_power(self, device, state):
ioloop = IOLoop.current()
ioloop.spawn_callback(self._power_dev, device, status)

async def add_device(self, dev, device):
await device.initialize()
self.devices[dev] = device


class GPIO:
gpio_root = "/sys/class/gpio"

Expand Down Expand Up @@ -187,7 +176,6 @@ async def setup_pin(pin, active_low=1):
if GPIO._get_gpio_option(pin, "direction").strip() != "out":
GPIO._set_gpio_option(pin, "direction", "out")


@staticmethod
def is_pin_on(pin):
return "on" if int(GPIO._get_gpio_option(pin, "value")) else "off"
Expand All @@ -198,5 +186,25 @@ def set_pin_value(pin, active):
GPIO._set_gpio_option(pin, "value", value)


class GpioDevice:
def __init__(self, dev, config):
self.name = config.get(dev + "_name", dev)
self.status = None
self.pin = config.getint(dev + "_pin")
self.active_low = int(config.getboolean(dev + "_active_low", False))

async def initialize(self):
logging.debug(f"Attempting to configure pin GPIO{self.pin}")
await GPIO.setup_pin(self.pin, self.active_low)
await self.refresh_status()

async def refresh_status(self):
self.status = GPIO.is_pin_on(self.pin)

async def power(self, status):
await GPIO.verify_pin(self.pin, self.active_low)
GPIO.set_pin_value(self.pin, int(status == "on"))


def load_plugin(config):
return PrinterPower(config)