Skip to content

Commit

Permalink
Merge pull request #3 from matmair/working-0.2.2
Browse files Browse the repository at this point in the history
Improve assigment
  • Loading branch information
matmair authored Jun 25, 2023
2 parents a14a9df + 095b519 commit f1cc756
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 5 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "inventree-wled-locator"
version = "0.2.1"
version = "0.2.2"
description="Use WLED to locate InvenTree StockLocations."
readme = "README.md"
license = {text = "MIT license"}
Expand Down
80 changes: 76 additions & 4 deletions src/inventree_wled_locator/WledPlugin.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
"""Use WLED to locate InvenTree StockLocations.."""

import json
import logging

import requests
from common.notifications import NotificationBody
from django.conf.urls import url
from django.contrib.auth import get_user_model
from django.core.validators import MinValueValidator
from django.http import JsonResponse
from django.shortcuts import redirect
from django.urls import reverse
from django.utils.translation import ugettext_lazy as _
Expand All @@ -18,6 +20,11 @@
logger = logging.getLogger('inventree')


def superuser_check(user):
"""Check if a user is a superuser."""
return user.is_superuser


class WledPlugin(UrlsMixin, LocateMixin, SettingsMixin, InvenTreePlugin):
"""Use WLED to locate InvenTree StockLocations.."""

Expand Down Expand Up @@ -56,8 +63,8 @@ def locate_stock_location(self, location_pk):

try:
location = StockLocation.objects.get(pk=location_pk)
led_nbr = location.get_metadata('wled_led')
if led_nbr:
led_nbr = int(location.get_metadata('wled_led'))
if led_nbr is not None:
self._set_led(led_nbr)
else:
# notify superusers that a location has no LED number
Expand All @@ -69,20 +76,85 @@ def locate_stock_location(self, location_pk):

def view_off(self, request):
"""Turn off all LEDs."""
if not superuser_check(request.user):
raise PermissionError("Only superusers can turn off all LEDs")

self._set_led()
return redirect(self.settings_url)

def view_unregister(self, request, pk):
"""Unregister an LED."""
if not superuser_check(request.user):
raise PermissionError("Only superusers can turn off all LEDs")

try:
item = StockLocation.objects.get(pk=pk)
item.set_metadata('wled_led', None)
except StockLocation.DoesNotExist:
pass
return redirect(self.settings_url)

def view_register(self, request, pk=None, led=None, context=None):
"""Register an LED."""
if not superuser_check(request.user):
raise PermissionError("Only superusers can turn off all LEDs")

if pk is None and led is None and str(request.body, encoding='utf8') == '':
return JsonResponse({'actions': {'POST': ['stocklocation', 'led', ], }})
elif request.body is not None:
data = json.loads(request.body)
pk = data.get('stocklocation')
led = data.get('led')

try:
item = StockLocation.objects.get(pk=pk)
item.set_metadata('wled_led', led)
except StockLocation.DoesNotExist:
pass
return redirect(self.settings_url)

def setup_urls(self):
"""Return the URLs defined by this plugin."""
return [
url(r'off/', self.view_off, name='off'),
url(r'unregister/(?P<pk>\d+)/', self.view_unregister, name='unregister'),
url(r'register/(?P<pk>\d+)/(?P<led>\w+)/', self.view_register, name='register'),
url(r'register/', self.view_register, name='register-simple'),
]

def get_settings_content(self, request):
"""Add context to the settings panel."""
stocklocations = StockLocation.objects.filter(metadata__isnull=False).all()

target_locs = [{'name': loc.pathstring, 'led': loc.get_metadata('wled_led'), 'id': loc.id} for loc in stocklocations if loc.get_metadata('wled_led')]
stock_strings = ''.join([f"""<tr>
<td>{a["name"]}</td>
<td>{a["led"]}</td>
<td><a class="btn btn-primary" href="{reverse("plugin:inventree-wled-locator:unregister", kwargs={"pk": a["id"]})}">unregister</a></td>
</tr>""" for a in target_locs])
return f"""
<h3>WLED controlls</h3>
<p>Turn off all LEDs: <a href="{reverse('plugin:inventree-wled-locator:off')}">turn off</a></p>
<a class="btn btn-primary" href="{reverse('plugin:inventree-wled-locator:off')}">Turn off</a>
<button class="btn btn-primary" onclick="led_register()">Register LED</button>
<table class="table table-striped">
<thead><tr><th>Location</th><th>LED</th><th>Actions</th></tr></thead>
<tbody>{stock_strings}</tbody>
</table>
<script>
function led_register() {{
constructForm('{reverse("plugin:inventree-wled-locator:register-simple")}', {{
title: 'Register LED',
actions: 'POST',
method: 'POST',
url: '{reverse("plugin:inventree-wled-locator:register-simple")}',
fields: {{
'stocklocation': {{'model': 'stocklocation', label: 'Location', type: 'related field', api_url: '{reverse("api-location-list")}', required: true, }},
'led': {{'label': 'LED', 'type': 'integer', 'min': 0, 'max': {self.get_setting("MAX_LEDS")} }},
}},
}});
}}
</script>
"""

def _set_led(self, target_led: int = None):
Expand All @@ -95,5 +167,5 @@ def _set_led(self, target_led: int = None):
requests.post(base_url, json={"seg": {"i": [0, self.get_setting("MAX_LEDS"), color_black]}})

# Turn on target led
if target_led:
if target_led is not None:
requests.post(base_url, json={"seg": {"i": [target_led, color_marked]}})

0 comments on commit f1cc756

Please sign in to comment.