feat: add dynamic printer configuration manager

Co-authored-by: aider (openai/DeepSeek-V3.2-Thinking) <aider@aider.chat>
This commit is contained in:
dxc
2026-02-11 14:14:59 +08:00
parent 5f3ceef3fd
commit c6fd0aca90
3 changed files with 72 additions and 8 deletions

View File

@ -3,6 +3,7 @@ import base64
import os
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont
from .print_config import PrintConfigManager
# 引入二维码生成库
try:
@ -12,8 +13,7 @@ except ImportError:
class LabelPrintService:
PRINTER_IP = "192.168.9.221"
PRINTER_PORT = 9100
# Printer IP and port now managed by PrintConfigManager
# ================= 1. 尺寸与分辨率配置 (300 DPI) =================
DOTS_PER_MM = 12 # 300 DPI
@ -271,8 +271,9 @@ class LabelPrintService:
@staticmethod
def send_to_printer(data):
ip = LabelPrintService.PRINTER_IP
port = LabelPrintService.PRINTER_PORT
config = PrintConfigManager.get_config('label_printer')
ip = config['ip']
port = config['port']
try:
# 1. 获取 RGB 图像

View File

@ -1,11 +1,13 @@
import socket
import datetime
from .print_config import PrintConfigManager
class NetworkPrintService:
def __init__(self, ip='192.168.9.250', port=9100):
self.ip = ip
self.port = port
def __init__(self, ip=None, port=None):
config = PrintConfigManager.get_config('network_printer')
self.ip = ip if ip is not None else config['ip']
self.port = port if port is not None else config['port']
def _send_to_printer(self, content):
"""

View File

@ -0,0 +1,61 @@
import json
import os
from pathlib import Path
class PrintConfigManager:
CONFIG_FILENAME = 'printer_config.json'
DEFAULT_CONFIG = {
'label_printer': {'ip': '192.168.9.221', 'port': 9100},
'network_printer': {'ip': '192.168.9.250', 'port': 9100}
}
@classmethod
def _get_config_path(cls):
# Determine the path relative to this file's directory
current_dir = Path(__file__).parent
return current_dir / cls.CONFIG_FILENAME
@classmethod
def get_config(cls, printer_type='label_printer'):
"""
Retrieve configuration for a given printer type.
Returns a dict with 'ip' and 'port'.
"""
config_path = cls._get_config_path()
if not config_path.exists():
# Write default config if not exists
cls.save_config(cls.DEFAULT_CONFIG)
config = cls.DEFAULT_CONFIG
else:
try:
with open(config_path, 'r', encoding='utf-8') as f:
config = json.load(f)
except Exception as e:
print(f"Error reading printer config: {e}")
config = cls.DEFAULT_CONFIG
# Return specific printer config, falling back to default for that type
printer_config = config.get(printer_type, cls.DEFAULT_CONFIG.get(printer_type))
# Ensure it's a dict with ip and port
if not printer_config or 'ip' not in printer_config:
printer_config = cls.DEFAULT_CONFIG.get(printer_type, {'ip': '127.0.0.1', 'port': 9100})
return printer_config
@classmethod
def save_config(cls, new_config):
"""
Save entire config dictionary to file.
new_config should be a dict with keys 'label_printer' and/or 'network_printer'.
"""
config_path = cls._get_config_path()
try:
# If file exists, merge existing with new
existing = {}
if config_path.exists():
with open(config_path, 'r', encoding='utf-8') as f:
existing = json.load(f)
existing.update(new_config)
with open(config_path, 'w', encoding='utf-8') as f:
json.dump(existing, f, indent=2)
except Exception as e:
print(f"Error saving printer config: {e}")
raise