Compare commits

...
Sign in to create a new pull request.

24 commits

Author SHA1 Message Date
a5ce162530
fix(install): Add requests as dependency 2024-04-21 21:57:06 -04:00
85981d81b5
feat(label): Switch to POST request 2024-04-21 21:55:38 -04:00
1cf5a58807
fix(label): Change code to more reflect the mixin 2024-04-21 21:40:35 -04:00
9460d923c9
fix(label): Call print_label for everry label 2024-04-21 21:27:36 -04:00
0156cf18a5
fix(label): Fix django imports 2024-04-21 21:16:36 -04:00
c5d55e79b2
feat(label): Add print_labels for multiple labels 2024-04-21 21:10:51 -04:00
7dc96c65ff
chiore(tmpl): Add empty placeholder template 2024-04-21 21:10:18 -04:00
bfaa0b7f89
feat(barcode): Add barcode support 2024-04-20 22:42:17 -04:00
fbfb35634e
feat(label): Add location 2024-04-20 22:10:22 -04:00
8572cccf9f
fix(label): Check if attributes exist 2024-04-20 22:06:09 -04:00
fdea2b70d1
fix(label): Add type info to label 2024-04-20 21:58:33 -04:00
43c5c8a5ba
feat(label): Switch to custom barcode with numbers only 2024-04-20 21:51:01 -04:00
a732fb3d4a
fix(label): Socket sending 2024-04-18 01:04:11 -04:00
77864ba979
fix(label): Remove qr_data 2024-04-18 01:00:50 -04:00
f44590a9f5
fix(label): Serialize only a few fields 2024-04-18 00:53:43 -04:00
b52ee09b90
fix(label): Try another way to serialize 2024-04-18 00:44:12 -04:00
536d27d272
feat(label): Switch to JSON 2024-04-18 00:39:06 -04:00
b333e1577c
fix(test): Fix test server to actually save the code 2024-04-17 22:23:16 -04:00
cf7003aa9a
fix(label): Use buffer for image 2024-04-17 22:07:05 -04:00
b29acedffd
fix(label): Remove encode, it should already be encoded 2024-04-17 21:55:45 -04:00
60f3d79e73
fix(label): Encode label to png before sending 2024-04-17 21:54:13 -04:00
86b1c9c1a7
fix(label): Name of plugin file 2024-04-17 21:40:36 -04:00
aadadd8ebf
feat(printer): Add basic printer plugin implementation 2024-04-17 21:32:39 -04:00
8b0dd6aedd
Initial commit 2024-04-17 21:07:18 -04:00
9 changed files with 448 additions and 0 deletions

231
.gitignore vendored Normal file
View file

@ -0,0 +1,231 @@
# Created by https://www.toptal.com/developers/gitignore/api/macos,python,visualstudiocode
# Edit at https://www.toptal.com/developers/gitignore?templates=macos,python,visualstudiocode
# File generated by test server
test.*
### macOS ###
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### macOS Patch ###
# iCloud generated files
*.icloud
### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
### Python Patch ###
# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
poetry.toml
# ruff
.ruff_cache/
# LSP config files
pyrightconfig.json
### VisualStudioCode ###
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets
# Local History for Visual Studio Code
.history/
# Built Visual Studio Code Extensions
*.vsix
### VisualStudioCode Patch ###
# Ignore all local history of files
.history
.ionide
# End of https://www.toptal.com/developers/gitignore/api/macos,python,visualstudiocode

21
LICENSE Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2024 Sergal.engineering
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

3
README.md Normal file
View file

@ -0,0 +1,3 @@
# inventree-phomemo-plugin
TBD

9
empty.html Normal file
View file

@ -0,0 +1,9 @@
{% extends "label/label_base.html" %}
{% block style %}
<!-- You can write custom CSS here -->
{% endblock %}
{% block content %}
<!-- HTML content goes here! -->
{% endblock %}

View file

View file

@ -0,0 +1,133 @@
# django
from django.utils.translation import gettext_lazy as _
from django.core.validators import MinValueValidator
from django.core.validators import MaxValueValidator
from django.http import JsonResponse
# printer support
import requests
# barcode helpers
from InvenTree.helpers_model import getModelsWithMixin
from InvenTree.models import InvenTreeBarcodeMixin
# InvenTree plugin libs
from plugin import InvenTreePlugin
from plugin.mixins import LabelPrintingMixin, SettingsMixin, BarcodeMixin
from label.models import LabelTemplate
from inventree_phomemo.version import PHOMEMO_PLUGIN_VERSION
class PhomemoLabelPlugin(LabelPrintingMixin, BarcodeMixin, SettingsMixin, InvenTreePlugin):
AUTHOR = "Sergal.engineering"
DESCRIPTION = "Label printing plugin for Phomemo printers"
VERSION = PHOMEMO_PLUGIN_VERSION
NAME = "Phomemo"
SLUG = "phomemo"
TITLE = "Phomemo Label Printer"
SETTINGS = {
'URL': {
'name': _('URL'),
'description': _('URL of the print endpoint'),
'default': 'http://localhost:8080/print',
},
}
def get_fields(self, label_instance):
object_to_print = label_instance.object_to_print
match label_instance.SUBDIR:
case 'part':
tpart = object_to_print
barcode = '1' + str(object_to_print.pk)
case 'stockitem':
tpart = object_to_print.part
barcode = '2' + str(object_to_print.pk)
case 'stocklocation':
tpart = object_to_print
barcode = '3' + str(object_to_print.pk)
case 'build':
tpart = object_to_print
barcode = '4' + str(object_to_print.pk)
case _:
tpart = object_to_print
barcode = '0' + str(object_to_print.pk)
print(f"!! Unsupported item type: {label_instance.SUBDIR}")
fields = {
'name': tpart.name,
'description': tpart.description,
'pk': tpart.pk,
'params': tpart.parameters_map() if hasattr(tpart, 'parameters_map') else None,
'category': tpart.category.name if hasattr(tpart, 'category') else None,
'category_path': tpart.category.pathstring if hasattr(tpart, 'category') else None,
'barcode': barcode,
'type': label_instance.SUBDIR,
'width': label_instance.width,
'height': label_instance.height
}
return fields
def print_labels(self, label: LabelTemplate, items: list, request, **kwargs):
outputs = []
# Get label content for every label
for item in items:
label.object_to_print = item
outputs.append(self.get_fields(label))
# Read settings
url = self.get_setting('URL')
# Send the label to the printer
r = requests.post(url, json=outputs)
r.raise_for_status()
return JsonResponse({
'success': True,
'message': f'{len(items)} labels printed',
})
@staticmethod
def get_supported_barcode_models():
"""Returns a list of database models which support barcode functionality."""
return getModelsWithMixin(InvenTreeBarcodeMixin)
def format_matched_response(self, label, model, instance):
"""Format a response for the scanned data."""
return {label: instance.format_matched_response()}
def scan(self, barcode_data):
# Our barcode should be a string
if type(barcode_data) is not str:
barcode_data = str(barcode_data)
# Our barcodes are at least two symbols long
if len(barcode_data) < 2:
return
match barcode_data[0]:
case '1':
model_type = 'part'
case '2':
model_type = 'stockitem'
case '3':
model_type = 'stocklocation'
case '4':
model_type = 'build'
supported_models = self.get_supported_barcode_models()
for model in supported_models:
label = model.barcode_model_type()
if label == model_type:
try:
pk = int(barcode_data[1:])
instance = model.objects.get(pk=pk)
return self.format_matched_response(label, model, instance)
except (ValueError, model.DoesNotExist):
pass

View file

@ -0,0 +1,22 @@
# server.py
# simple listener to an IP port to test the phomemo plugin
import socket
PORT = 9100 # Port to listen on
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', PORT))
s.listen(1)
while True:
conn, addr = s.accept()
print(addr)
printer = open('test.json', 'wb')
while True:
data = conn.recv(91000)
print('data received')
print('Sending to printer...')
printer.write(data)
if not data:
break
printer.close()

View file

@ -0,0 +1 @@
PHOMEMO_PLUGIN_VERSION = "0.0.0"

28
setup.py Normal file
View file

@ -0,0 +1,28 @@
from setuptools import setup, find_packages
from inventree_phomemo.version import PHOMEMO_PLUGIN_VERSION
with open('README.md', encoding='utf-8') as f:
long_description = f.read()
setup(
name = "inventree-phomemo-plugin",
version = PHOMEMO_PLUGIN_VERSION,
author = "Sergal.engineering",
author_email = "zener@theserg.al",
license = "MIT",
description = "Phomemo label plugin for InvenTree",
long_description = long_description,
long_description_content_type = 'text/markdown',
keywords = "inventree phomemo label plugin",
url = "https://git.merp.digital/sergal-engineering/inventree-phomemo-plugin/",
packages = find_packages(),
scripts = [],
install_requires = ['requests'],
entry_points = {
'inventree_plugins': [ 'PhomemoLabelPlugin = inventree_phomemo.phomemo_label:PhomemoLabelPlugin' ]
}
)