inventree-phomemo-plugin/inventree_phomemo/phomemo_label.py

77 lines
2.4 KiB
Python

# translation
from django.utils.translation import gettext_lazy as _
from django.core.validators import MinValueValidator
from django.core.validators import MaxValueValidator
# printer supportt
import socket
import io
import json
# InvenTree plugin libs
from plugin import InvenTreePlugin
from plugin.mixins import LabelPrintingMixin, SettingsMixin
from inventree_phomemo.version import PHOMEMO_PLUGIN_VERSION
class PhomemoLabelPlugin(LabelPrintingMixin, 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 = {
'IP_ADDRESS': {
'name': _('IP Address'),
'description': _('IP address of phomemo print server'),
'default': '',
},
'PORT': {
'name': _('Port'),
'description': _('Port of phomemo print server'),
'default': '9100',
},
}
def print_label(self, **kwargs):
# Read settings
ip_address = self.get_setting('IP_ADDRESS')
port = int(self.get_setting('PORT'))
object_to_print = kwargs['label_instance'].object_to_print
key = object_to_print.pk
kind = ''
if kwargs['label_instance'].SUBDIR == 'part':
tpart = object_to_print
kind = 'part'
elif kwargs['label_instance'].SUBDIR == 'stockitem':
tpart = object_to_print.part
kind = 'stockitem'
else:
print(f"!! Unsupported item type: {object_to_print.SUBDIR}")
return
fields = {
'name': tpart.name,
'description': tpart.description,
'pk': tpart.pk,
'params': tpart.parameters_map(),
'category': tpart.category.name,
'category_path': tpart.category.pathstring,
'kind': kind,
'ppk': key
}
# Send the label to the printer
try:
print_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print_socket.settimeout(5)
print_socket.connect((ip_address, port))
json.dump(fields, print_socket)
print_socket.close()
except Exception as error:
raise ConnectionError('Error connecting to printer server: ' + str(error))