C #-based Linux shared printing control method and system, medium and product

By combining a C#-based printing daemon with a WebSocket server and a user-space USB communication library, the stability and compatibility issues in cross-platform remote printing control were resolved. This resulted in efficient and flexible printing control, reduced development and maintenance costs, and improved system reliability and user experience.

CN122018831AInactive Publication Date: 2026-05-12BEIJING SHUOFANG INFORMATION TECH CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
BEIJING SHUOFANG INFORMATION TECH CO LTD
Filing Date
2026-04-14
Publication Date
2026-05-12
Estimated Expiration
Not applicable · inactive patent

AI Technical Summary

Technical Problem

Existing remote printing control solutions in multi-device, cross-platform environments suffer from problems such as poor stability, high maintenance complexity, difficulty in device adaptation, and complex access control, making it difficult to meet the needs of industrial applications.

Method used

This print daemon, developed in C#, is registered as an operating system-level service. It communicates with remote clients via a WebSocket server, parses JSON-formatted instructions, draws images using a cross-platform graphics rendering library, and communicates directly with the printer via a user-mode USB communication library. It dynamically requests permissions and persists rules, achieving cross-platform, stable, and efficient print control.

Benefits of technology

It achieves efficient, flexible, and stable cross-platform print control, reduces development and maintenance costs, improves system scalability and real-time response capabilities, and ensures reliable execution of print jobs and user experience.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122018831A_ABST
    Figure CN122018831A_ABST
Patent Text Reader

Abstract

The invention discloses a C #-based Linux shared printing control method and system, a medium and a product, and relates to the technical field of printing control. The method comprises the following steps: creating and operating a WebSocket server through a printing daemon; analyzing a JSON format printing instruction in the printing message through the printing daemon, and obtaining canvas parameters and a content drawing instruction; creating a virtual canvas in a memory based on the canvas parameters, generating to-be-printed image data according to the content drawing instruction, and adding a printing task containing the to-be-printed image data into a concurrent queue; and the printing tasks in the concurrent queue are sequentially processed through the printing daemon, and for each printing task, after the printing task is packaged into a bottom-layer instruction in a preset format through the USB interface with the obtained permission and the user-mode USB communication library, the bottom-layer instruction is directly sent to a printer to execute printing. By implementing the technical scheme, the effect of efficient, flexible and stable Linux shared printing control is achieved.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application relates to the field of print control, and in particular to a Linux shared print control method, system, media, and product based on C#. Background Technology

[0002] In today's era of digital office work and frequent information exchange, printing demands are increasing, especially in multi-device, cross-platform environments, making efficient and stable printing control crucial. With the continuous development of computer and network technologies, remote printing has become an important means of improving work efficiency and convenience. Among existing technologies, solutions for remote printing needs mainly include the following: The first approach is a browser plugin-based printing solution. This solution allows web pages to call the local system's printing interface by installing ActiveX, NPAPI, or PPAPI plugins in the browser. However, with increasingly stringent browser security policies, mainstream browsers have gradually phased out support for traditional plugins. Furthermore, the plugin method relies on the browser process; when the browser closes or the plugin crashes, the printing job will be interrupted and cannot be automatically resumed, making it difficult to meet the stability requirements of industrial applications.

[0003] The second approach is to directly integrate printing functionality into the client application. This solution requires users to install specific client software locally, which is responsible for communicating with the remote system and calling the local printing interface. The drawbacks of this approach are: printing interfaces differ significantly across operating system platforms, making the maintenance of multi-platform clients costly; the client is tightly coupled with the business system, requiring synchronous updates when business logic changes, increasing deployment and maintenance complexity; and the client program typically runs as a normal application process, lacking an exception recovery mechanism, meaning printing service is interrupted if the process unexpectedly exits.

[0004] Therefore, there is an urgent need for a printing control solution that can solve the above-mentioned technical problems. Summary of the Invention

[0005] This application provides a Linux shared print control method, system, media, and product based on C#, achieving efficient, flexible, and stable Linux shared print control.

[0006] Firstly, this application provides a Linux shared print control method based on C#, which includes: Register the printing daemon as an operating system-level service, and create and run a WebSocket server through the printing daemon to establish a communication connection with a remote client. When a print message is received from the remote client via the WebSocket server, the print daemon parses the JSON format print instructions in the print message to obtain canvas parameters and content drawing instructions. Based on the canvas parameters, a virtual canvas is created in memory, and according to the content drawing instructions, a cross-platform graphics rendering library is called to draw text, barcodes, or images on the virtual canvas to generate image data to be printed, and the printing task containing the image data to be printed is added to the concurrent queue. The print daemon processes print tasks in the concurrent queue sequentially. For each print task, the user-mode USB communication library detects the current system's access permissions to the target USB printer. If the permissions are insufficient, temporary permissions are dynamically requested through the operating system's authorization service, and the permission rules are persisted to the system's device management rules. Through the USB interface with the obtained permissions, the user-mode USB communication library encapsulates the print task into a preset format of low-level instructions and sends it directly to the printer for printing.

[0007] The above technical solution employs C# to implement the core logic of the daemon in a cross-platform runtime environment. Utilizing high-level abstract syntax and rich class library resources for business development significantly reduces development complexity and maintenance costs, while improving code readability and sustainable iteration capabilities. Through dynamic permission application and persistence mechanisms, it overcomes the permission barriers to USB device access in domestic systems, enhancing the system's versatility and promotional value. A unified communication protocol using WebSocket server and JSON format commands provides standardized printing service interfaces for various remote clients; the daemon performs data parsing, image rendering, and task scheduling locally, decoupling the remote system from the underlying printing device and improving system scalability and real-time response capabilities. Direct access to the printer via a user-space USB communication library bypasses the operating system's underlying driver framework, avoiding the security risks associated with direct kernel interface calls.

[0008] In some embodiments, persisting the permission rules to the system device management rules includes: The device descriptor of the target USB printer is obtained through the user-mode USB communication library. The device descriptor includes a supplier identifier, a product identifier, and a serial number. Based on the acquired device information, a device permission rule containing multiple matching conditions is generated. The device permission rule identifies a single device by a serial number and assigns read and write permissions for a non-privileged user group to the identified device. The system commands are invoked with administrator privileges to write the device permission rules into the configuration file under the device management rules directory of the operating system, and a check is performed to see if there are any conflicting rules before writing. The system invokes the device management commands provided by the operating system to reload all the device permission rules and trigger device events, so that the new rules take effect immediately. At the same time, it verifies whether the permissions are successfully applied by re-enumerating the devices and persists the successfully authorized printer information to the local configuration file so that the saved permission configuration can be applied when the system starts up or the device is plugged in or unplugged.

[0009] By employing the above technical solution, device permission rules containing precise matching conditions are generated by obtaining the printer's device descriptor. These rules uniquely identify a single device using its serial number, preventing permission rule conflicts or misconfigurations when multiple printers of the same model are connected, thus achieving fine-grained permission management for each printer. A conflict rule check is performed before writing the device permission rules to the system configuration file to prevent permission configuration failures or system device management anomalies due to rule conflicts. After the rules take effect, device re-enumeration verifies successful permission application, ensuring the integrity and reliability of the configuration process. Successfully authorized printer information is persisted to the local configuration file, ensuring that permission rules automatically take effect after system restarts or printer re-plugging / unplugging, eliminating the need for repeated authorization. Users only need to complete authorization once upon first use, and can use the service seamlessly afterwards, significantly improving the user experience. Through a standardized device permission rule generation and writing process, the device management mechanisms of different Linux distributions are adapted, enabling the print daemon to run stably in various operating system environments. Administrators do not need to manually configure complex system permissions, reducing deployment difficulty and maintenance costs.

[0010] In some embodiments, the method further includes: Based on the priority field in the JSON format print instruction, the print task is inserted into the corresponding position in the concurrent queue to realize the queue-jumping processing of high-priority tasks; After successfully adding the print job to the concurrent queue, if the request confirmation flag is true, the WebSocket server returns a confirmation message to the client containing the job ID and the estimated waiting time for the current queue position. If an event occurs during the execution of the printing task that allows for progress feedback, an intermediate status update containing the task ID, execution progress percentage, and remaining estimated time will be pushed to the client via the WebSocket server. After the printing task is completed or fails, a final status report containing the task ID, execution result, time consumption statistics and detailed error codes is generated and asynchronously pushed to the client through the WebSocket server.

[0011] By adopting the above technical solution and parsing the priority field in the JSON printing command, high-priority tasks can be inserted into the corresponding positions in the concurrent queue, enabling priority processing of urgent printing tasks. This mechanism ensures that critical business operations can be executed first when batch printing tasks are backlogged, meeting the differentiated needs of different business scenarios for printing timeliness. After a task is added to the queue, if the client requests a confirmation, a confirmation message containing the task ID and the estimated waiting time in the queue is returned immediately, allowing users to know immediately that the task has been accepted and the estimated completion time. Combined with intermediate status pushes during the execution process (progress percentage, remaining time), users can keep track of the task progress in real time, avoiding anxiety or duplicate submissions due to missing information. The task ID is used throughout the entire lifecycle of task reception, queuing, execution, and completion, establishing a traceable and unique identifier for each printing task. The final status report includes the execution result, time consumption statistics, and detailed error codes, providing the business system with accurate task completion credentials, facilitating subsequent auditing, statistics, or anomaly investigation, and achieving closed-loop management of printing operations.

[0012] In some embodiments, the step of calling a cross-platform graphics rendering library according to the content drawing instructions to draw text, barcodes, or images on the virtual canvas to generate image data to be printed specifically includes: Based on the canvas parameters, initialize the memory canvas of the cross-platform graphics rendering library, and set the rendering resolution based on the DPI parameters of the target USB printer; According to the order of the content drawing instructions, the text, vector barcode and decoded image are rendered sequentially on the memory canvas to form a grayscale image; A preset edge enhancement algorithm is applied to the grayscale image to identify and sharpen the boundary regions between text and graphics in order to compensate for ink dot diffusion during the thermal printing process. For the edge-enhanced grayscale image, based on the physical characteristics of the thermal printhead of the target USB printer, a preset adaptive jitter algorithm is applied to dynamically adjust the jitter matrix parameters and generate a monochrome bitmap for the target USB printer. The monochrome bitmap is segmented according to the minimum print line unit of the target USB printer and encapsulated into a raster bitmap printing instruction stream conforming to the native protocol.

[0013] By employing the above technical solution, the rendering resolution is set by acquiring the DPI parameters of the target USB printer, ensuring that the generated image data precisely matches the printer's physical output precision, thus avoiding image blurring or size distortion caused by resolution mismatch. Combined with adaptation to the physical characteristics of the thermal printhead, the image rendering result is deeply integrated with the printer's hardware capabilities, guaranteeing print quality from the source. Addressing the inherent ink dot diffusion problem in thermal printing, an edge enhancement algorithm is applied to identify and sharpen the boundary areas of text and graphics, effectively compensating for the physical diffusion effect of ink dots on thermal paper. This results in sharp text edges and clear barcode boundaries, significantly improving the readability of barcodes, QR codes, and other content requiring high precision. Based on the physical characteristics of the target printer's thermal printhead, an adaptive dithering algorithm dynamically adjusts the dithering matrix parameters, rather than using a fixed halftone processing scheme. This mechanism ensures that the same original image achieves optimal printing results on different printer models, avoiding inconsistent print quality due to device differences and achieving true personalized intelligent adaptation.

[0014] In some embodiments, based on the physical characteristics of the thermal printhead of the target USB printer, a preset adaptive jitter algorithm is applied to dynamically adjust the jitter matrix parameters to generate a monochrome bitmap for the target USB printer, specifically including: The physical characteristic parameters of the thermal printhead of the target USB printer are obtained, including printhead resolution, heating dot density, single-point heating time curve, and thermal diffusivity of adjacent heating points. Based on the thermal diffusivity, a thermal diffusivity model is constructed to predict the range of heat impact of each printing point on adjacent pixels during the printing process; Based on the aforementioned thermal diffusion model, pre-compensation calculations are performed on each pixel in the monochrome bitmap, and the heating intensity of the current pixel is dynamically adjusted according to the printing status of adjacent pixels to counteract the blurring effect caused by thermal diffusion. Based on the historical printing data of the target USB printer, the optimal jitter matrix parameters under different ambient temperatures are statistically analyzed, and a mapping relationship between ambient temperature and jitter matrix parameters is established. During the printing process, the current ambient temperature is collected in real time, and a matching dithering matrix is ​​dynamically selected according to the mapping relationship to perform halftone processing on the monochrome bitmap and generate the final monochrome bitmap.

[0015] By employing the above technical solution, a complete understanding of the printhead's working mechanism is established by acquiring the physical characteristic parameters of the thermal printhead of the target USB printer. A thermal diffusion model is constructed based on the thermal diffusivity coefficient to accurately predict the heat impact range of each print point on adjacent pixels during printing, laying the physical foundation for precise print quality optimization. Based on the thermal diffusivity model, pre-compensation calculations are performed on each pixel in the monochrome bitmap, dynamically adjusting the heating intensity of the current pixel according to the printing status of adjacent pixels. This mechanism performs reverse compensation for the expected diffusion effect before heat is actually generated, ensuring that the final dot matrix presented on the thermal paper is precisely consistent with the actual desired image, fundamentally eliminating problems such as blurred text and barcode adhesion caused by lateral heat diffusion. During the printing process, the current ambient temperature is collected in real time, and a matching dithering matrix is ​​dynamically selected for halftone processing based on this mapping relationship. This mechanism ensures that the same printer can output consistent print quality in both high-temperature summer and low-temperature winter environments, eliminating the impact of ambient temperature changes on print quality.

[0016] In some embodiments, the step of sequentially processing the print tasks in the concurrent queue through the print daemon includes: After retrieving a print job from the concurrent queue, a pre-print diagnostic command is sent to the target USB printer through the user-mode USB communication library. The pre-print diagnostic command includes a comprehensive query of the printer's internal buffer status, printhead temperature, and remaining paper level. Receive and parse the diagnostic response data of the target USB printer in response to the pre-print diagnostic command, and establish the state vector of the target USB printer; The state vector is input into a preset expert rule engine, which determines whether the current state is suitable for continuing printing based on a historical fault mode library, and predicts the possible fault types. If it is determined that printing is not suitable or a high-risk failure is predicted, the corresponding processing strategy is executed according to the output of the rule engine, including pausing the current queue or putting the task back to the head of the queue and marking it as requiring manual intervention. If the printer is deemed suitable for printing, the printing task will continue, and the printer's real-time status feedback will be continuously monitored during the printing process.

[0017] By employing the above technical solution, the current health status of the target USB printer is obtained by sending a comprehensive query command containing information on the internal buffer status, printhead temperature, and remaining paper level. This mechanism detects potential problems before data transmission, preventing print job failures or printer damage due to abnormal printer status (such as paper shortage, overheating, or a full buffer), thus enabling early detection and avoidance of problems. The rule engine, combined with a historical fault pattern library, can not only determine whether the current state is suitable for continuing printing but also predict possible fault types based on historical data. This mechanism upgrades traditional passive fault response to proactive fault prediction, significantly improving the system's intelligence level. Based on the output of the expert rule engine, the system can execute differentiated processing strategies: for temporary anomalies (such as a full buffer), the task can be placed back at the head of the queue for retry; for severe anomalies (such as paper shortage or printhead overheating), the entire queue is paused and marked as requiring manual intervention. This mechanism avoids system crashes or blind retries due to a single task anomaly, ensuring the robust operation of the overall system.

[0018] In some embodiments, the method further includes: The user-space USB communication library enumerates all connected USB printers, creates a device object for each USB printer, and collects performance parameters, including maximum printing speed, resolution, current number of tasks, and historical failure rate. Based on the collected performance parameters, a real-time load weight is dynamically calculated for each printer, and a consistent hash ring is constructed based on the real-time load weight for task routing decisions. The set of candidate printers that meet the printing conditions is selected by matching the print quality requirement field in the JSON format print command with the performance parameters of each USB printer. For each print job to be processed, the optimal target USB printer is selected by consistent hashing algorithm based on the hash value of the job identifier and the real-time load weight of the candidate printers, and the job is routed to the concurrent queue dedicated to the target USB printer. When processing each concurrent queue, the real-time load and task completion status of each USB printer are continuously monitored, the real-time load weight is dynamically adjusted and the consistent hash ring is updated to achieve adaptive load balancing among multiple printers.

[0019] The above technical solution dynamically calculates the real-time load weight for each printer based on collected performance parameters, and constructs a consistent hashing ring based on this weight for task routing decisions. The introduction of the consistent hashing algorithm ensures that when the number of printers changes (added or removed), only a small number of tasks need to be remapped, avoiding large-scale task migration and ensuring system stability and scalability. By parsing the print quality requirement field in the JSON print command and matching it with the performance parameters of each printer, a set of candidate printers meeting the printing conditions is formed. This mechanism ensures that tasks with special print quality requirements (such as high-resolution images and fine barcodes) can be routed to printers with the corresponding capabilities, avoiding substandard print quality due to insufficient equipment capabilities. During the processing of each concurrent queue, the real-time load and task completion status of each printer are continuously monitored, its load weight is dynamically adjusted, and the consistent hashing ring is updated in real time. This closed-loop feedback mechanism enables the system to automatically adjust the task allocation strategy according to the actual working status of each printer, avoiding overloading one printer while other printers are idle, achieving globally optimal utilization of multi-printer resources, and improving overall print throughput.

[0020] In a second aspect, embodiments of this application provide a computer system including a memory, a processor, and a computer program stored in the memory; the processor executes the computer program to implement the steps of the method described in any possible implementation of the first aspect.

[0021] Thirdly, embodiments of this application provide a computer-readable storage medium having a computer program / instructions stored thereon, which, when executed by a processor, implement the steps of the method described in any possible implementation of the first aspect.

[0022] Fourthly, embodiments of this application provide a computer program product, including a computer program / instructions, which, when executed by a processor, implement the steps of the method described in any possible implementation of the first aspect.

[0023] It is understood that the computer system provided in the second aspect, the storage medium provided in the third aspect, and the computer program product provided in the fourth aspect are all used to execute the method provided in this application. Therefore, the beneficial effects they can achieve can be referred to the beneficial effects in the corresponding methods, and will not be repeated here.

[0024] One or more technical solutions provided in the embodiments of this application have at least the following technical effects or advantages: 1. By registering the printing daemon as an operating system-level service, it can run persistently in the background and achieve automatic startup on boot and automatic restart in case of abnormalities, solving the problems of traditional printing programs that rely on user login or manual startup and cannot be recovered after a crash. Furthermore, based on the C# language and its cross-platform runtime environment, this daemon can run seamlessly on various Linux distributions, eliminating the need to develop and maintain multiple versions for different operating systems, significantly reducing development costs and maintenance complexity. 2. By creating and running a WebSocket server, a unified network access point is provided for remote clients. WebSocket's full-duplex communication supports real-time, low-latency data transmission, solving the problems of low efficiency and poor real-time performance associated with traditional HTTP polling. Printing commands are encapsulated in JSON format, giving the communication protocol good readability and extensibility. Clients developed in different languages ​​can easily interface with it, achieving standardized decoupling between the remote system and the local printing device.

[0025] 3. A virtual canvas is created in memory, and text, barcodes, or images are drawn using a cross-platform graphics rendering library, decoupling the generation process of print content from the specific printer model. Regardless of the brand or model of the target printer, it is uniformly processed as image data to be printed, solving the adaptation difficulties caused by differences in printer instruction sets in traditional solutions. At the same time, the rendered print job is added to a concurrent queue to achieve asynchronous processing of the task, avoiding network communication blockage due to long printing times and improving the overall system response speed; 4. Communicating directly with the printer via the user-space USB communication library bypasses the operating system's own printer driver framework, avoiding reliance on system-level printing services such as CUPS. Addressing the common issue of ordinary users lacking access to USB device nodes under domestic operating systems, the solution dynamically requests temporary permissions through the operating system's authorization service when insufficient permissions are detected, and persists the permission rules to the system device management rules. This mechanism allows the daemon to access the printer stably and persistently as a non-privileged user, resolving the permission issue while avoiding the security risks associated with running as root, ensuring availability and security on domestic systems such as Kylin and UnionTech. Attached Figure Description

[0026] Figure 1 This is a flowchart illustrating the Linux shared printing control method based on C# in an embodiment of this application; Figure 2 This is a schematic diagram of the process for generating image data to be printed in an embodiment of this application; Figure 3 This is a schematic diagram of an exemplary hardware structure of a computer system in an embodiment of this application. Detailed Implementation

[0027] The terminology used in the following embodiments of this application is for the purpose of describing particular embodiments only and is not intended to be limiting of this application. As used in the specification and appended claims of this application, the singular expressions “a,” “an,” “the,” “the,” “the,” and “this” are intended to include the plural expressions as well, unless the context clearly indicates otherwise. It should also be understood that the term “and / or” as used in this application refers to any or all possible combinations including one or more of the listed items.

[0028] Hereinafter, the terms "first" and "second" are used for descriptive purposes only and should not be construed as implying or suggesting relative importance or implicitly indicating the number of indicated technical features. Thus, a feature defined as "first" or "second" may explicitly or implicitly include one or more of that feature, and in the description of the embodiments of this application, unless otherwise stated, "multiple" means two or more.

[0029] The following is combined with Figure 1 The method of the embodiments of this application will be described below.

[0030] Please see Figure 1 This is a flowchart illustrating a Linux shared print control method based on C# in an embodiment of this application. The method includes the following steps: S101. Register the printing daemon as an operating system-level service, and create and run a WebSocket server through the printing daemon to establish a communication connection with a remote client. S102. When a print message is received from the remote client through the WebSocket server, the print daemon parses the JSON format print instructions in the print message to obtain the canvas parameters and content drawing instructions. S103. Based on the canvas parameters, create a virtual canvas in memory, and according to the content drawing instructions, call a cross-platform graphics rendering library to draw text, barcodes, or images on the virtual canvas to generate image data to be printed, and add the printing task containing the image data to be printed to a concurrent queue. S104. The print daemon processes the print tasks in the concurrent queue sequentially. For each print task, the user-mode USB communication library detects the current system's access permissions to the target USB printer. If the permissions are insufficient, the system dynamically requests temporary permissions through the operating system's authorization service and persists the permission rules to the system's device management rules. Through the USB interface with the obtained permissions, the user-mode USB communication library encapsulates the print task into a preset format of low-level instructions and sends it directly to the printer for printing.

[0031] For computer devices equipped with domestically developed operating systems (such as Kylin and UnionTech UOS), the printing daemon is written in C# and compiled into an executable file using the .NET Core cross-platform runtime environment. To achieve automatic startup and automatic recovery from errors, the daemon is registered as an operating system-level service: on systems supporting systemd, the `.service` unit file is written with the parameters `Restart=always` and `RestartSec=5s` to enable automatic system restart after a crash or exit; on systems not supporting systemd, similar functionality is achieved through init scripts or corresponding service management mechanisms. After the daemon starts, it creates and runs a WebSocket server instance, listening on a preset network port (e.g., 8080). This WebSocket server acts as a unified network access point, waiting for connection requests from various remote clients (including web applications, mobile applications, cross-platform desktop clients, etc.). When a client successfully connects, the connection is managed as an independent session instance, ensuring communication isolation between different clients and preventing cross-connections. The full-duplex communication feature of the WebSocket protocol provides the embodiments of this application with low-latency and high-efficiency data transmission capabilities, which significantly reduces network overhead and response latency compared to the traditional HTTP polling mechanism.

[0032] After the remote client establishes a connection with the WebSocket server, the client sends print messages according to a predefined protocol format. This embodiment uses JSON format to encapsulate print instructions, offering good readability, extensibility, and cross-language compatibility. Upon receiving a print message, the daemon first determines the message type (text or binary), then deserializes and parses the JSON string to extract canvas parameters and content drawing instructions. Canvas parameters include canvas size (width, height), resolution (DPI), print orientation (portrait / landscape), margins, etc., used for subsequent virtual canvas creation. Content drawing instructions are an ordered array of instructions, each containing content type (text / barcode / image), content data, position coordinates, and style parameters (font, size, color, etc.). Through this structured instruction format, the remote client can flexibly describe arbitrarily complex print layouts without needing to concern itself with the underlying printer's specific instruction set.

[0033] Based on the parsed canvas parameters, the daemon creates a virtual canvas in memory. This embodiment uses SkiaSharp as a cross-platform graphics rendering library, supporting multiple platforms such as Windows, Linux (including domestic operating systems), and macOS, and providing high-quality 2D graphics rendering capabilities. Based on the DPI information in the canvas parameters, the rendering resolution of the virtual canvas is set to ensure that the subsequently generated image data accurately matches the physical output precision of the printer. Following the order of content drawing instructions, text, barcodes / QR codes, and images are drawn sequentially on the virtual canvas. For binary output devices such as thermal printers, directly outputting grayscale images may result in blurry printing effects. Therefore, this embodiment can perform optimization processing before generating the final image data. After generating the image data to be printed, it is encapsulated with information such as task ID, priority, and retry count into a print task object. Then, the print task is added to a thread-safe concurrent queue. This embodiment uses ConcurrentQueue. <t>Implemented as a queue, and synchronized with the ManualResetEventSlim semaphore for thread synchronization. After a task is added to the queue, the daemon can return a "task received" confirmation message to the client (if the client requests a receipt), and then continue processing the next network request. The actual printing execution is completed asynchronously by a background thread, decoupling network communication from printing execution and avoiding network service blocking due to long printing times.

[0034] The daemon maintains a dedicated background printing thread, which continuously monitors the concurrent queue as a consumer. This thread performs the following operations in a loop: waits for the ManualResetEventSlim semaphore, and is awakened when the queue is not empty; calls the TryDequeue method to retrieve a print job from the queue; executes the print job, and checks if the queue is empty after execution; if it is, the semaphore is reset; if an exception occurs during execution, the exception is caught and logged to ensure that the thread does not crash. In domestic operating systems (such as Kylin and UnionTech UOS), ordinary users do not have permission to access USB device nodes (such as / dev / bus / usb / xxx) by default. To solve this problem, this application embodiment designs a dynamic permission request mechanism: attempting to open the target USB printer through the user-space USB communication library (libusb-1.0). libusb is a cross-platform user-space USB library that allows applications to communicate directly with USB devices without writing kernel drivers. If the open operation returns a permission error code, a permission request process is initiated: the operating system's authorization service (such as Polkit) is invoked, a graphical authorization dialog box is displayed to the currently logged-in user, and temporary privilege escalation is requested. After successful user authorization, the printer device file is opened with the temporarily escalated privileges, and the opened file descriptor is passed to the daemon via inter-process communication. The daemon receives and holds the file descriptor, thus maintaining access to the printer as a regular user, without needing to run as root for an extended period. To avoid re-authorization after each reboot or device re-plugging, this embodiment persists the permission rules to the system device management rules. After gaining access, the daemon uses the libusb library through the opened USB interface to encapsulate the image data to be printed into low-level instructions that the printer can recognize. For thermal receipt printers, the monochrome bitmap usually needs to be encapsulated according to the GS v 0 format of the ESC / POS instruction set, and the corresponding instruction header and control code are added. The encapsulated instruction data is then sent to the printer's output endpoint through libusb's batch transfer or interrupt transfer method. The entire process communicates directly with the USB printer, completely bypassing the operating system's own print driver framework (such as CUPS), avoiding compatibility issues and performance losses caused by system-level print services, and achieving end-to-end pass-through from the remote client to the local printer.

[0035] In some embodiments, persisting the permission rules to the system device management rules includes: The device descriptor of the target USB printer is obtained through the user-mode USB communication library. The device descriptor includes a supplier identifier, a product identifier, and a serial number. Based on the acquired device information, a device permission rule containing multiple matching conditions is generated. The device permission rule identifies a single device by a serial number and assigns read and write permissions for a non-privileged user group to the identified device. The system commands are invoked with administrator privileges to write the device permission rules into the configuration file under the device management rules directory of the operating system, and a check is performed to see if there are any conflicting rules before writing. The system invokes the device management commands provided by the operating system to reload all the device permission rules and trigger device events, so that the new rules take effect immediately. At the same time, it verifies whether the permissions are successfully applied by re-enumerating the devices and persists the successfully authorized printer information to the local configuration file so that the saved permission configuration can be applied when the system starts up or the device is plugged in or unplugged.

[0036] Once the daemon successfully opens the printer with temporary permissions, it immediately obtains the complete device descriptor of the printer through the user-mode USB communication library. libusb provides a standard USB descriptor query interface, which can obtain information including but not limited to the following: (1) Vendor identifier: The unique identifier of the USB device manufacturer, such as 0x04b8 representing EPSON. (2) Product identifier: The identifier of different product models under the same manufacturer, such as 0x0202. (3) Serial number: The unique serial number of each device under the same model, used to accurately distinguish multiple printers of the same model. (4) Device class, subclass, protocol: Used to further limit the device type, ensuring that the rule only applies to the printer and not other USB devices. (5) Interface descriptor: Printers usually have multiple interfaces (such as printing interface, scanning interface), and it is necessary to specify the specific interface used for printing. The purpose of obtaining this information is to achieve accurate device matching and avoid affecting the normal use of other USB devices due to overly broad rules. Based on the obtained device descriptor, a device permission rule containing multiple matching conditions is dynamically generated. Taking udev rule as an example, the typical rule format is as follows: SUBSYSTEM=="usb",ATTRS{idVendor}=="04b8",ATTRS{idProduct}=="0202",ATTRS{serial}=="12345678",MODE="0660",GROUP="plugdev". The meaning of this rule is as follows: SUBSYSTEM=="usb": Limited to the USB subsystem. ATTRS{idVendor}=="04b8": Matches devices with vendor ID 0x04b8. ATTRS{idProduct}=="0202": Matches devices with product ID 0x0202. ATTRS{serial}=="12345678": Matches devices with serial number 12345678 (accurate to a single device). MODE="0660": Sets the device file permissions to 660 (owner read / write, group read / write). GROUP="plugdev": Sets the device file's group to plugdev, allowing users within that group to access it. Through precise serial number matching, even if multiple printers of the same model connect simultaneously, independent rules can be generated for each device, preventing interference. Furthermore, the rule includes matching conditions such as device class and interface, further ensuring that it only applies to the printer interface.

[0037] After generating the rule text, the daemon needs to write it to the operating system's device management rules directory. In Linux systems, udev rules are usually stored in the ` / etc / udev / rules.d / ` directory, and filenames generally begin with a number (e.g., `99-usb-printer.rules`) to control the loading order. The writing process requires administrator privileges, which the daemon achieves by: calling system-provided privileged execution mechanisms (such as `pkexec`, `sudo`, or an auxiliary process running directly as root) to write the rule text to the target file; before writing, the program reads all existing rule files in the target directory to check for potentially conflicting rules. The conflict determination logic includes: whether there are rules for the same device (the same combination of VID / PID / serial number); and whether there are rules with higher priority that might overwrite this rule. If a conflict is found, it is handled according to a predefined policy: either overwrite the old rule (based on the latest authorization), merge the rules (preserving the valid conditions of both), or abort the writing and prompt the user. The purpose of conflict checking is to avoid permission configuration failures due to rule conflicts and to ensure that the written rules can be correctly recognized and applied by the system. After the rule files are written, the system needs to be notified to reload all rules and make the new rules effective for connected devices. The daemon calls the device management commands provided by the operating system to complete this operation: (1) Reload rules: Execute the command udevadm control --reload-rules to make the system reread all rule files in the / etc / udev / rules.d / directory. (2) Trigger device events: Execute the command udevadmtrigger to make the system reapply the newly loaded rules to all existing devices. For printers that are already connected, this command will immediately update the permissions and group of their device files to the values ​​specified by the new rules. With these two commands, the newly written permission rules take effect immediately without restarting the system or unplugging and replugging the devices. After the rules take effect, the daemon needs to verify whether the permissions have been successfully applied to ensure that subsequent printing tasks can proceed normally: Re-enumerate the devices through libusb and try to open the printer again (using normal user permissions). If it opens successfully, it means that the permission rules have been applied correctly; if it still returns a permission error, it means that the rule writing or loading has failed, and it is necessary to record the error log and possibly roll back the operation. If verification fails, the daemon can attempt to re-execute the write and load process or issue an alert to the user. Upon successful verification, the successfully authorized printer information is persisted to a local configuration file. The configuration file includes: the printer's VID, PID, and serial number; the path and content of the generated rule file; the authorization timestamp; and the device alias (e.g., "Office HP Printer"), which can be customized by the user.The purpose of persistent configuration is: (1) Automatic recovery after system restart: When the daemon starts, it first reads the local configuration file and checks whether the printer recorded therein is connected. If it is connected and the corresponding udev rule exists, it will try to open it directly without authorization. (2) Automatic matching after device plugging and unplugging: When the printer is unplugged and plugged back in, the system will automatically set the correct permissions according to the existing udev rules. The daemon only needs to detect the device connection to use it directly.

[0038] In some embodiments, the method further includes: Based on the priority field in the JSON format print instruction, the print task is inserted into the corresponding position in the concurrent queue to realize the queue-jumping processing of high-priority tasks; After successfully adding the print job to the concurrent queue, if the request confirmation flag is true, the WebSocket server returns a confirmation message to the client containing the job ID and the estimated waiting time for the current queue position. If an event occurs during the execution of the printing task that allows for progress feedback, an intermediate status update containing the task ID, execution progress percentage, and remaining estimated time will be pushed to the client via the WebSocket server. After the printing task is completed or fails, a final status report containing the task ID, execution result, time consumption statistics and detailed error codes is generated and asynchronously pushed to the client through the WebSocket server.

[0039] In the JSON format printing command, an optional priority field is added to identify the urgency of the task. The priority field can be defined in several ways: (1) Numerical level: such as 1-10, the larger the number, the higher the priority. (2) Enumeration type: such as high, normal, low. In order to realize priority queueing, the concurrent queue cannot be a simple FIFO (first in first out) queue, but needs to support priority sorting. The embodiments of this application adopt one of the following two implementation methods: (1) Priority queue. Use the ConcurrentPriorityQueue data structure (which can be implemented based on a heap or skip list), and sort the queue internally according to priority. When a new task is added, it is inserted into the corresponding position in the queue according to its priority value, with higher priority tasks at the front. (2) Multi-level queue. Maintain an independent FIFO queue for each priority level (such as high priority queue, normal priority queue, low priority queue). When the background printing thread is processing, it takes tasks from the high priority queue first, and only processes the next level queue when the high priority queue is empty. Once the daemon parses the `priority` field, it performs the following operations: If a priority queue is used, tasks are directly inserted into the corresponding positions in the queue according to their priority, automatically placing high-priority tasks before low-priority tasks; if a multi-level queue is used, tasks are placed into the corresponding sub-queues based on their priority values; for tasks with the same priority, they are arranged in order of arrival time to ensure fairness. Through this mechanism, urgent tasks can "jump the queue" before ordinary tasks, meeting the business's timeliness requirements.

[0040] The requireReceipt field in the JSON command is a boolean flag indicating whether the client requests a task confirmation receipt. If the field is true, the daemon needs to immediately return a confirmation message to the client after queuing the task. The confirmation message contains the following key information: (1) Task ID: consistent with the ID submitted by the client, used by the client to match the confirmation message with the original request. (2) Task status: fixed as "RECEIVED" or "QUEUED", indicating that the task has been received. (3) Queue position: the current task's position in the queue (e.g., "There are 3 tasks ahead of you"). (4) Estimated waiting time: calculated based on the total estimated processing time of the tasks ahead in the queue. The estimated waiting time is calculated as follows: Estimated waiting time = index of the current task in the queue × average task processing time. The average task processing time is a dynamic statistical value. The daemon will continuously record the execution time of historical tasks and maintain a sliding window average. For example, if the average processing time of the first 20 tasks is 2 seconds, and there are 5 tasks ahead of the current task, the estimated waiting time is approximately 10 seconds. The confirmation message is returned immediately through the current WebSocket connection, still in JSON format. Upon receiving the confirmation message, the client can immediately notify the user that "the print job has been submitted and is expected to wait 10 seconds," improving the user experience.

[0041] During the execution of a printing task, progress feedback is not available at all times. This application defines the following events as "events with progress feedback": (1) Task begins execution: The background printing thread retrieves the task from the queue and prepares to send data. (2) Page printing complete: For multi-page printing tasks, each page is sent after completion. (3) Percentage node: For large printing tasks, feedback can be set at 10%, 20%...90% completion. (4) Key stage completion: Such as "Data sending complete", "Waiting for printer response", "Print confirmation received", etc. (5) Printer status change: Such as the printer changing from "Busy" to "Ready", or from "Ready" to "Printing". Intermediate status messages contain the following information: (1) Task ID: Identifies the task to which the message belongs. (2) Event type: Such as "STARTED", "PROGRESS", etc. (3) Progress percentage: If applicable, indicates the current percentage completed. (4) Elapsed time: The time elapsed since the task began execution. (5) Remaining estimated time: The remaining time estimated based on the completed portion and the overall task volume. (6) Additional information: Descriptive text such as "Page 3 has been printed". In order to prevent excessive pushes from causing network congestion, this application embodiment controls the frequency of intermediate status pushes: For tasks that are completed quickly (e.g., total time < 5 seconds), only "start" and "complete" events are pushed; for tasks that take a long time, a minimum push interval (e.g., at least 1 second) is set to avoid high-frequency pushes. The client can customize the frequency of status feedback through the reportInterval field in the instruction. There are two possible final statuses for a task: (1) Successful completion: All data of the printing task has been successfully sent to the printer and confirmation has been received from the printer (if applicable). (2) Failure termination: The task cannot continue to be executed for various reasons, including: printer malfunction (out of paper, paper jam, offline), communication error (USB disconnection, timeout), data format error, user cancellation, and exceeding the retry limit. The final status report contains complete task execution information: (1) Task ID: The unique identifier of the task. (2) Final status: SUCCESS or FAILED. (3) Execution result description: such as "Printing completed successfully" or "Printing failed: Printer out of paper". (4) Detailed error code: For failure cases, return the specific error code for easy programmatic handling by the client. (5) Time consumption statistics: queue waiting time, actual execution time, total time consumption. (6) Number of retries: the number of times the task was actually retried. (7) Timestamp: the time when the task ended. The final status report is asynchronously pushed to the client by the daemon through a WebSocket connection.

[0042] Figure 2 This is a schematic diagram of the process for generating image data to be printed in an embodiment of this application, such as... Figure 2 As shown, the step of calling a cross-platform graphics rendering library according to the content drawing instructions to draw text, barcodes, or images on the virtual canvas to generate image data to be printed specifically includes: S201. According to the canvas parameters, initialize the memory canvas of the cross-platform graphics rendering library, and set the rendering resolution based on the DPI parameters of the target USB printer. S202. According to the order of the content drawing instructions, render the text, vector barcode and decoded image on the memory canvas in sequence to form a grayscale image; S203. Apply a preset edge enhancement algorithm to the grayscale image to identify and sharpen the boundary regions between text and graphics in order to compensate for ink dot diffusion during the thermal printing process. S204. Based on the physical characteristics of the thermal printhead of the target USB printer, the grayscale image after edge enhancement is dynamically adjusted by applying a preset adaptive jitter algorithm to generate a monochrome bitmap for the target USB printer. S205. Divide the monochrome bitmap into the smallest print line unit of the target USB printer and encapsulate it into a raster bitmap printing instruction stream that conforms to the native protocol.

[0043] According to the canvas parameters parsed from the JSON printing instructions, the daemon creates a virtual canvas in memory. This canvas is not physically existing, but a two-dimensional pixel matrix used to carry the content to be drawn later. The core parameters of the canvas include the canvas size, background color and color depth. DPI is the core physical parameter of the printer, which determines the fineness of the printed output. Common thermal printer DPIs include 203 DPI, 300 DPI, etc. After obtaining the DPI, it is set as the rendering resolution of the canvas. The contentInstructions in the JSON instructions is an array, and the order of the array elements determines the order of drawing. According to the type field of each instruction, the daemon calls different rendering sub-modules: (1) Text rendering. The font is selected according to the font field (such as "SimHei", "Microsoft YaHei") in the instruction. Since some fonts may be missing in domestic operating systems, the system has a built-in font fallback mechanism: when the specified font does not exist, it automatically searches for and uses the backup fonts that exist in the system, such as "Noto Sans CJK SC" (Source Han Sans), to ensure that Chinese characters are displayed normally. Convert the text string into a glyph outline according to the specified font, size, and style (bold / italic), and fill it with black pixels. Draw the glyph onto the specified position on the canvas according to the coordinates in the instruction. (2) Barcode / QR code rendering. Call the barcode generation library to generate the corresponding code image from the content string in the instruction according to the specified format (such as CODE128, QR_CODE). The code image is usually a black and white binary bitmap. Scale the generated code image to the width and height specified in the instruction, and then draw it onto the specified position on the canvas. Leave enough blank area (quiet area) around the barcode to ensure that the barcode can be read normally. (3) Image rendering. The content in the instruction is usually Base64 encoded image data. The daemon first decodes the Base64 string to obtain the original image byte stream. According to the format field in the instruction or the image file header, identify the image format (PNG, JPEG, BMP, etc.) and call the corresponding decoder. Scale the decoded image to the size specified in the instruction, and then draw it onto the canvas. Use a high-quality interpolation algorithm (such as bicubic interpolation) during the scaling process to minimize image distortion. After all content is drawn, the image in the memory canvas remains in 24-bit true color format. For subsequent processing, it is first converted to a grayscale image. Thermal printers work by heating tiny heating points on the print head, causing a chemical reaction that changes the color of the coating on the thermal paper. To compensate for ink dot diffusion, this embodiment applies an edge enhancement algorithm to the grayscale image before sending it to the printer. The core idea is to artificially enhance the transition areas from light to dark in the image, so that the diffusion effect of the printer output precisely counteracts this enhancement, ultimately presenting clear edges.The specific implementation includes the following sub-steps: (1) Gradient calculation. Convolution operation is performed on the grayscale image to calculate the gradient value (rate of change) of each pixel in the horizontal and vertical directions. The area with a large gradient value is the edge area. (2) Edge recognition. According to whether the gradient value exceeds the preset threshold, the pixels are classified as: strong edge points, with a large gradient value, usually the boundary between text strokes and background; weak edge points, with a medium gradient value, possibly the texture or gradient inside the graphic; non-edge points, with a very small gradient value, belonging to flat areas. Morphological dilation operation is applied to the identified edge points to connect adjacent edge points to form a continuous edge contour. Different degrees of sharpening are applied according to the edge type: (1) Text edges: A stronger sharpening kernel is applied to significantly enhance the contrast between text strokes and background. (2) Graphic edges: A milder sharpening kernel is applied to enhance the edge while maintaining a smooth transition inside the graphic, avoiding unnatural jagged edges.

[0044] Traditional dithering algorithms use a fixed dithering matrix (such as a 4×4 Bayer matrix), operating the same way for all images and all printers. The innovation of this application lies in dynamically adjusting the dithering matrix parameters based on the physical characteristics of the target printer's thermal printhead, achieving a personalized optimal dithering effect for the device. Using the selected dithering matrix, the edge-enhanced grayscale image is halftoned to generate a final monochrome bitmap. Each pixel is represented by 1 bit: 0 for white, 1 for black. The generated monochrome bitmap is a complete two-dimensional pixel matrix. To send it to the printer via USB, it needs to be segmented into data units conforming to the printer's protocol. Thermal printers typically receive data in "rows," with the number of pixels per row related to the physical width of the printhead (e.g., 80mm wide, 203 DPI corresponds to approximately 640 pixels). The daemon segments the monochrome bitmap into several rows according to this width. The daemon then encapsulates the segmented monochrome bitmap according to the instruction format supported by the target printer, forming a complete binary instruction stream. To support multiple printer models, the daemon designed a protocol adaptation layer: (1) Printer driver configuration: Each printer model corresponds to a configuration file, which describes the instruction set, parameter format, and restrictions supported by the printer. (2) Instruction factory: Based on the model of the target printer, the corresponding instruction wrapper is dynamically selected to convert the standardized "print this line bitmap" request into a specific printer instruction byte stream.

[0045] In some embodiments, based on the physical characteristics of the thermal printhead of the target USB printer, a preset adaptive jitter algorithm is applied to dynamically adjust the jitter matrix parameters to generate a monochrome bitmap for the target USB printer, specifically including: The physical characteristic parameters of the thermal printhead of the target USB printer are obtained, including printhead resolution, heating dot density, single-point heating time curve, and thermal diffusivity of adjacent heating points. Based on the thermal diffusivity, a thermal diffusivity model is constructed to predict the range of heat impact of each printing point on adjacent pixels during the printing process; Based on the aforementioned thermal diffusion model, pre-compensation calculations are performed on each pixel in the monochrome bitmap, and the heating intensity of the current pixel is dynamically adjusted according to the printing status of adjacent pixels to counteract the blurring effect caused by thermal diffusion. Based on the historical printing data of the target USB printer, the optimal jitter matrix parameters under different ambient temperatures are statistically analyzed, and a mapping relationship between ambient temperature and jitter matrix parameters is established. During the printing process, the current ambient temperature is collected in real time, and a matching dithering matrix is ​​dynamically selected according to the mapping relationship to perform halftone processing on the monochrome bitmap and generate the final monochrome bitmap.

[0046] After establishing communication with the printer via the user-mode USB communication library, the daemon sends specific query commands to the printer to obtain the printhead resolution (number of heating points per inch), heating dot density (number of heating points within the physical width of the printhead, determining the maximum print width), and single-point heating time curve (time required for a heating point to reach the target temperature from power-on, and the cooling curve after power-off). The thermal diffusivity is a core parameter of adaptive jitter and cannot be directly read; it needs to be obtained indirectly through the following methods: having the printer print a series of isolated single-point, double-point, and multi-point patterns; capturing the print results with a scanner or high-resolution camera and analyzing the actual size and shape of the printed dots; comparing the difference between the theoretical expected point and the actual printed dots to establish a mathematical model to deduce the thermal diffusivity. For example, if printing an isolated single dot actually forms a circle with a radius of 3 pixels on the paper, then the thermal diffusivity radius can be deduced to be 3. The obtained physical characteristic parameters are bound to the printer's serial number and persistently stored in a local configuration file. Subsequent times the printer is used, the saved parameters are read directly, eliminating the need for repeated measurements. Based on the obtained thermal diffusivity coefficient, a thermal diffusivity model is constructed to predict the thermal impact of each printing point on adjacent pixels during the printing process. A commonly used model is a two-dimensional Gaussian distribution: H(d) = A × exp(-d² / 2σ²). Here, H(d) represents the heat contribution at a distance d from the center point; A represents the maximum heat at the center point (normalized to 1); σ represents the thermal diffusivity coefficient, which determines the heat diffusion range; and d represents the Euclidean distance from the center point. For discrete pixel grids, a thermal diffusivity kernel can be pre-calculated, such as a 5×5 or 7×7 matrix, representing the influence weight of the heat from the center pixel on each surrounding pixel. To ensure model accuracy, calibration is required based on actual printing results: print a series of known patterns, such as a checkerboard or grayscale gradient bars, scan the printed results, compare them with the actual expected values, and adjust model parameters (such as the σ value) to minimize the error between the model's prediction and the actual measurement. The final output of the thermal diffusivity model is an influence matrix used for subsequent pre-compensation calculations.

[0047] Since thermal diffusion is a complex physical process, the pre-compensation image cannot be solved in one step using a simple mathematical formula. This application employs an iterative approximation method to solve the problem step by step: the desired image itself is used as the initial guess value for the pre-compensation image. The currently guessed pre-compensation image is convolved with the thermal diffusion kernel to simulate the image that the printer will actually display after heating. The simulated image is compared pixel-by-pixel with the desired image, and the difference between the two is calculated to obtain an error image. In the error image, positive values ​​indicate that the simulation result is too dark (heating needs to be reduced), and negative values ​​indicate that the simulation result is too light (heating needs to be increased). Based on the error image, the pre-compensation image is corrected. The principle of correction is: if the simulation result is too dark in a certain area, it means that the area is overheated and the heating intensity of the corresponding pixel needs to be reduced; if the simulation result is too light, it means that the heating is insufficient and the heating intensity needs to be increased. The magnitude of the correction is determined by both the error value and the thermal diffusion kernel. The corrected pre-compensation image is used as the new guess value, and the above steps are repeated. As the number of iterations increases, the simulation result will get closer and closer to the desired image. When the maximum value of the error image is lower than the preset threshold (e.g., the difference in grayscale value is less than 5) or the number of iterations reaches the upper limit (e.g., 20 times), the iteration stops, and the current pre-compensated image is the final result. In the actual calculation process, the following special cases need to be considered: (1) Image boundary processing. The embodiments of this application use the following method: For the part that exceeds the boundary, it is assumed that the outside of the image is pure white (no heating) and does not participate in the calculation of heat diffusion. During iterative correction, the correction amount of edge pixels is only based on the error feedback of the internal region of the image. (2) Heating intensity constraint. The embodiments of this application set the pixel value range to 0-255, where 0 represents no heating and 255 represents the maximum heating intensity. During the iteration process, if the calculated value of a certain pixel exceeds 255, it is truncated to 255, and the excess part is redistributed to the adjacent pixels to ensure the total heating energy is conserved. (3) Convergence acceleration strategy. To improve computational efficiency, this application employs the following acceleration strategies: fine iteration is performed only in high-frequency regions of the image (such as text edges and graphic boundaries), while flat regions converge quickly; a multi-resolution strategy is adopted: the solution is first solved quickly on a low-resolution version, and then the result is used as an initial guess for the high-resolution solution. After the iterative solution is completed, a new grayscale image is output through pre-compensation calculation. After the pre-compensation calculation is completed, the output pre-compensated image is passed to the next processing stage—the adaptive dithering algorithm. The dithering algorithm converts this pre-compensated grayscale image into the binary instruction stream that the printer will ultimately execute.

[0048] The resistance of the printhead changes with temperature, resulting in varying amounts of heat generated under the same heating voltage. Specifically: as temperature increases, printhead resistance decreases, current increases at the same voltage, heating is stronger, and print dots are larger; as temperature decreases, printhead resistance increases, heating is weaker, and print dots are smaller. To establish a mapping relationship between temperature and optimal jitter parameters, the daemon continuously collects data during long-term operation: It collects the current ambient temperature via the system interface or temperature sensor before each print; it evaluates print quality through user feedback or automatic analysis (such as barcode reading success rate); and it stores the temperature, jitter parameters used, and quality score for each print in a database. For each temperature range (e.g., 18-20℃, 20-22℃, etc.), it analyzes all historical print samples within that range: if a certain jitter parameter combination repeatedly achieves high-quality scores at that temperature, it is marked as a candidate optimal parameter. As the sample size increases, machine learning algorithms (such as cluster analysis) automatically identify the optimal parameter combination for each temperature range. Before each print job, the daemon obtains the current ambient temperature and, based on the collected current temperature, searches for the corresponding optimal jitter parameters from the previously established mapping relationship. The selected dithering parameters are used to perform halftone processing on the pre-compensated image. Dithering algorithms can take several forms: (1) ordered dithering: using a temperature-adapted dithering matrix to convert grayscale images into binary images; (2) error diffusion: using a temperature-adapted diffusion coefficient (such as the weights of the Floyd-Steinberg algorithm) to compensate for the temperature effect during error diffusion. After printing, the temperature, dithering parameters, and quality feedback of this printing are added to the historical database as new samples for continuous optimization of the subsequent model.

[0049] In some embodiments, the step of sequentially processing the print tasks in the concurrent queue through the print daemon includes: After retrieving a print job from the concurrent queue, a pre-print diagnostic command is sent to the target USB printer through the user-mode USB communication library. The pre-print diagnostic command includes a comprehensive query of the printer's internal buffer status, printhead temperature, and remaining paper level. Receive and parse the diagnostic response data of the target USB printer in response to the pre-print diagnostic command, and establish the state vector of the target USB printer; The state vector is input into a preset expert rule engine, which determines whether the current state is suitable for continuing printing based on a historical fault mode library, and predicts the possible fault types. If it is determined that printing is not suitable or a high-risk failure is predicted, the corresponding processing strategy is executed according to the output of the rule engine, including pausing the current queue or putting the task back to the head of the queue and marking it as requiring manual intervention. If the printer is deemed suitable for printing, the printing task will continue, and the printer's real-time status feedback will be continuously monitored during the printing process.

[0050] The daemon sends a pre-print diagnostic command to the target printer through the user-mode USB communication library. This command is not a single command, but a combination of multiple standard query commands into a composite request to obtain multiple statuses in a single communication. Its core query dimensions include: (1) Printer internal buffer status: query the remaining space of the printer's receive buffer or the current queue length to determine whether new data can be received. (2) Printhead temperature: read the real-time temperature of the printhead to determine whether it is close to or exceeds the safety threshold. (3) Paper remaining amount: obtain information such as paper present, no paper, or paper running out through the paper sensor status. In addition, the diagnostic command can also be extended to query the cover status, ribbon remaining amount, error flags, etc., according to the printer model. The response data returned by the printer varies depending on the manufacturer and model, and may be a fixed-length status byte or a structured data block. The daemon parses the raw data according to the printer's protocol specifications and extracts key status fields. Then, these fields are mapped to a unified status vector. The state vector is a multi-dimensional numerical representation, including: buffer free percentage (0-100%), printhead temperature (degrees Celsius), paper status (encoded as: 0=paper present, 1=almost empty, 2=no paper), cover status (0=closed, 1=open), and error flag combinations. Through standardization, the subsequent rule engine can perform inference based on a unified input format, without needing to consider the differences between specific printers.

[0051] The state vector is fed into a pre-built expert rule engine. At its core is a rule base constructed from printing domain expert knowledge. Each rule includes a condition section (requirements for specific values ​​or ranges of the state vector) and a conclusion section (state assessment result, fault type prediction). For example: if the printhead temperature > 50°C, it is determined to be "overheating" and unsuitable for printing; if the paper status is "no paper," it is determined to be "out of paper" and unsuitable for printing; if the buffer idle percentage is < 10% and the task data volume is large, a "buffer overflow" fault is predicted; if the printhead temperature rises by more than 8°C in a short period, a "printhead overheating" fault is predicted. The rule base supports fuzzy matching and trend analysis, considering not only the current instantaneous value but also historical state changes (such as the rate of temperature rise) for prediction. In addition to static rules, the engine also associates with a historical fault pattern library. This library records the state vector sequences preceding previous printer faults and the final fault type. By comparing the current state vector with historical patterns, the engine can identify potential fault precursors. For example, if the current state vector is highly similar to the pattern before multiple "paper jam" failures in history, the engine will predict "high risk of paper jam". The rule engine combines the matched rules and historical patterns to output two key conclusions: (1) Whether it is suitable to continue printing: the conclusion is "suitable", "cautious" or "unsuitable". (2) Predicted failure type: such as no failure, overheating, paper shortage, paper jam, buffer overflow, etc. If the conclusion is "unsuitable" or a high-risk failure is predicted, the engine will also suggest a handling strategy (such as pause, retry, manual intervention).

[0052] If the rules engine determines that the current state is suitable for printing and no high-risk faults are predicted, the daemon immediately begins executing the print job, sending the print data to the printer via USB. However, monitoring does not stop even after printing begins. If printing is deemed unsuitable or a high-risk fault is predicted, the daemon executes corresponding strategies based on the engine's output suggestions: When a fault affects all tasks (e.g., printer offline, severe overheating), the daemon pauses retrieving new tasks from the concurrent queue and pushes an unavailability notification to the administrator or client; if the fault is limited to the current task and may be recoverable (e.g., buffer temporarily full), the task is put back at the head of the queue, and the retry count is increased, to be tried again the next time it is retrieved; for faults requiring user intervention (e.g., out of paper, paper jam), the task is marked as "awaiting manual intervention," the queue is paused, and a clear alarm is issued via logs, system notifications, or remote push notifications (e.g., "Printer out of paper, please add paper and continue"); if the system has multiple printers configured and the current printer is faulty, the daemon can reroute the task to other available printers for seamless switching.

[0053] For longer print jobs, the daemon sends data in chunks. After sending each chunk (e.g., several line bitmap data), it pauses briefly and then sends a simplified status query command to obtain the latest printer status. This segmented polling mechanism can promptly detect sudden anomalies during printing, such as paper jams or a sudden temperature rise. If an anomaly is detected during polling (e.g., a full buffer or excessive temperature), the daemon immediately pauses subsequent data transmission and takes action based on the anomaly type: if the anomaly is recoverable (e.g., a full buffer), it waits for a period before resuming transmission; if the anomaly is unrecoverable (e.g., a paper jam), it terminates the current task, records the reason for failure, and marks the task as failed (while simultaneously pushing a final status report); if the temperature is too high, it pauses transmission and waits for the temperature to drop to a safe range before automatically resuming. Based on the real-time occupancy of the printer buffer, the daemon dynamically adjusts the data transmission rate: accelerating transmission when the buffer is mostly empty and slowing down transmission when it is nearing full, avoiding overflow due to excessively fast transmission or inefficiency due to excessively slow transmission. After all data has been transmitted, the daemon sends a status query command again to confirm that the printer has completed processing the last batch of data and is error-free. If everything is normal, the task is marked as successful; if the printer reports an error (such as the last few lines not printing due to lack of paper), it is marked as a failure and the error code is recorded.

[0054] In some embodiments, the method further includes: The user-space USB communication library enumerates all connected USB printers, creates a device object for each USB printer, and collects performance parameters, including maximum printing speed, resolution, current number of tasks, and historical failure rate. Based on the collected performance parameters, a real-time load weight is dynamically calculated for each printer, and a consistent hash ring is constructed based on the real-time load weight for task routing decisions. The set of candidate printers that meet the printing conditions is selected by matching the print quality requirement field in the JSON format print command with the performance parameters of each USB printer. For each print job to be processed, the optimal target USB printer is selected by consistent hashing algorithm based on the hash value of the job identifier and the real-time load weight of the candidate printers, and the job is routed to the concurrent queue dedicated to the target USB printer. When processing each concurrent queue, the real-time load and task completion status of each USB printer are continuously monitored, the real-time load weight is dynamically adjusted and the consistent hash ring is updated to achieve adaptive load balancing among multiple printers.

[0055] When the daemon starts, it enumerates all connected USB printers using the user-space USB communication library. For each discovered printer, the system creates an independent device object. This device object is a digital twin of the printer at the software level, encapsulating all information related to the printer, including device identifier, communication handle, dedicated queue, and performance profile. Each printer's device object maintains a set of performance parameters, divided into static and dynamic parameters. Static performance parameters reflect the printer's inherent capabilities and are typically collected and persistently stored upon initial connection. These include: maximum print speed, such as 150 mm / s, which determines the upper limit of task execution speed; resolution, such as 203 DPI or 300 DPI, which determines print detail; supported media types, such as continuous paper, label paper, and black label paper; and instruction set type, such as ESC / POS or ZPL. Dynamic operating parameters reflect the printer's real-time status and are continuously updated during operation. These parameters include: current task count (the number of tasks waiting to be executed in the printer's dedicated queue); historical failure rate (the frequency of printer failures over a period of time, reflecting its reliability); average task time (the average execution time of historical tasks, used to estimate the completion time of new tasks); and current status (including online, offline, busy, idle, and faulty). Based on the collected performance parameters, a real-time load weight is dynamically calculated for each printer. The weight is not fixed but dynamically calculated based on the printer's real-time status. The calculation logic comprehensively considers basic capability weight, current load penalty, historical performance penalty, and status penalty. Basic capability weight: Printers with high resolution and high speed receive a higher basic weight. Current load penalty: Printers with a large number of current tasks have their weight appropriately reduced to avoid over-allocation. Historical performance penalty: Printers with high failure rates have their weight lowered, reducing task allocation to them. Status penalty: Offline printers have their weight set to zero, and faulty printers have their weight significantly reduced. For example, a high-resolution printer might initially have a weight of 100, but if there are currently 5 tasks waiting in the queue, each task reducing the weight by 5%, the final real-time weight could become 75. This dynamic calculation ensures that the weight accurately reflects the printer's current available capacity.

[0056] The system constructs a consistent hash ring based on the real-time weight of each printer. Consistent hashing is a special hash algorithm commonly used for load balancing in distributed systems. Its core idea is to map the printer weights to a virtual ring space (0 to 2). 32 -1 integer ring). Printers with higher weights occupy more virtual nodes on the ring, making them more likely to be selected. Each task is mapped to a point on the ring by the hash value of its task ID, and then the nearest virtual node is found clockwise. The printer to which the node belongs is the target printer. The advantage of consistent hashing is that when the number of printers changes (adding or removing printers), only a small number of tasks need to be remapped, and the routing of most tasks remains unchanged. This avoids a large number of task migrations caused by the addition or removal of printers and ensures the stability of the system. In the JSON format printing instructions, an optional qualityRequirement field is added to express the task's special requirements for printing quality. This field can contain a variety of constraints: (1) Minimum resolution requirement: such as "minDPI":300, which means that the task requires a printer with at least 300 DPI. (2) Media type requirement: such as "mediaType":"label", which means that a label paper printer is required. (3) Printing speed requirement: such as "maxSpeed":100, which means that the task has no special requirements for speed, but if the printer speed is too slow, it may affect efficiency. (4) Color Requirements: For example, "color": false indicates that only black and white printing is required. When a print job is received, the system first filters all connected printers based on their qualityRequirement field: checking whether the static performance parameters of each printer meet the job requirements. The set of printers obtained after filtering is called the candidate printer set. A job can only be assigned if the candidate set is not empty; if the candidate set is empty, an error is returned to the client, indicating that there is currently no available printer that meets the quality requirements.

[0057] For each print job to be processed, the system hashes its job ID string to obtain a hash value. Then, on the previously constructed consistent hash ring, starting from the position of this hash value, it searches clockwise. The first virtual node belonging to the candidate printer set encountered is the target printer for this job. This selection method ensures that: jobs with the same job ID are always routed to the same printer (beneficial for job relevance); printers with higher weights are more likely to be selected in the candidate set; and job routing migration is minimized when the candidate set changes. After the target printer is selected, the job is placed in the printer's dedicated concurrent queue. Each printer has its own independent queue, rather than all printers sharing a single queue. This queue isolation design brings multiple benefits: a printer failure will not block jobs on other printers; the current number of jobs on each printer directly reflects its load; and different scheduling priorities or retry policies can be set for different printers.

[0058] During system operation, the daemon continuously monitors the operational status of each printer. Based on the latest monitoring data, the system periodically (e.g., every minute) recalculates the real-time load weight of each printer. The weight adjustment logic includes: when a printer is offline or malfunctions, its weight is reset to zero or reduced to an extremely low level, preventing it from being assigned new tasks; when the printer queue becomes long, the weight is reduced proportionally to achieve overload protection; when a printer is idle for an extended period, its weight can be appropriately restored to attract more tasks; printers with high failure rates maintain a consistently low weight. After each weight update, the system needs to rebuild the consistent hash ring. Due to the characteristics of consistent hashing, changes in weight lead to adjustments in the distribution of virtual nodes on the ring, but only affect the allocation of subsequent new tasks; tasks already in the queue remain unaffected. This adjustment mechanism allows the system to continuously optimize during operation without interrupting ongoing printing tasks. When a printer suddenly goes offline or malfunctions, its weight immediately resets to zero, and the system rebuilds the hash ring after the next weight update. At this time, subsequent new tasks will no longer be routed to that printer. More importantly, for tasks already waiting in their dedicated queue but not yet executed, the system can perform failover: upon detecting a printer offline, all tasks in that queue are returned to the global allocation pool, and candidate set filtering and consistent hashing are re-executed for each task, routing them to other available printers. If a task cannot find a replacement printer due to quality requirements, it is marked as failed and the client is notified. This failover mechanism achieves high availability in a multi-printer environment, ensuring continued business operation even if a single printer fails.

[0059] The above describes the Linux shared printing control method based on C# in the embodiments of this application. The computer system in the embodiments of this application will be described in detail below in conjunction with the above Linux shared printing control method based on C#.

[0060] Please see Figure 3 This is a schematic diagram of an exemplary hardware structure of a computer system in an embodiment of this application.

[0061] In some embodiments, the computer system 300 includes a computer device, which may be a terminal device. The computer device includes a processor 301, a memory 302, a sensor module 303, a communication module 304, an input device 305, and an output device 306 connected via a system bus. The processor 301 of the computer device provides computing and control capabilities. The memory 302 of the computer device includes a non-volatile storage medium and internal memory. The non-volatile storage medium stores an operating system, computer programs, and a database. The internal memory provides an environment for the operation of the operating system and computer programs in the non-volatile storage medium. The database is used to store data.

[0062] Those skilled in the art will understand that Figure 3 The structure shown is merely a block diagram of a portion of the structure related to the present application and does not constitute a limitation on the computer device to which the present application is applied. Specific computer devices may include more or fewer components than those shown in the figure, or combine certain components, or have different component arrangements.

[0063] In some embodiments of this application, a computer-readable storage medium is provided, including instructions that, when executed on the computer system 300, cause the computer system 300 to execute the Linux shared print control method based on C# as described in this application.

[0064] In some embodiments of this application, a computer program product is also provided, which, when run on a computer system 300, causes the computer system 300 to execute the Linux shared printing control method based on C# in the embodiments of this application.

[0065] The above-described embodiments are only used to illustrate the technical solutions of this application, and are not intended to limit it. Although this application has been described in detail with reference to the foregoing embodiments, those skilled in the art should understand that modifications can still be made to the technical solutions described in the foregoing embodiments, or equivalent substitutions can be made to some of the technical features. Such modifications or substitutions do not cause the essence of the corresponding technical solutions to deviate from the scope of the technical solutions of the embodiments of this application.< / t>

Claims

1. A Linux shared printing control method based on C#, characterized in that, include: Register the printing daemon as an operating system-level service, and create and run a WebSocket server through the printing daemon to establish a communication connection with a remote client. When a print message is received from the remote client via the WebSocket server, the print daemon parses the JSON format print instructions in the print message to obtain canvas parameters and content drawing instructions. Based on the canvas parameters, a virtual canvas is created in memory, and according to the content drawing instructions, a cross-platform graphics rendering library is called to draw text, barcodes, or images on the virtual canvas to generate image data to be printed, and the printing task containing the image data to be printed is added to the concurrent queue. The print daemon processes print tasks in the concurrent queue sequentially. For each print task, the user-mode USB communication library detects the current system's access permissions to the target USB printer. If the permissions are insufficient, temporary permissions are dynamically requested through the operating system's authorization service, and the permission rules are persisted to the system's device management rules. Through the USB interface with the obtained permissions, the user-mode USB communication library encapsulates the print task into a preset format of low-level instructions and sends it directly to the printer for printing.

2. The method according to claim 1, characterized in that, The process of persisting permission rules to system device management rules includes: The device descriptor of the target USB printer is obtained through the user-mode USB communication library. The device descriptor includes a supplier identifier, a product identifier, and a serial number. Based on the acquired device information, a device permission rule containing multiple matching conditions is generated. The device permission rule identifies a single device by a serial number and assigns read and write permissions for a non-privileged user group to the identified device. The system commands are invoked with administrator privileges to write the device permission rules into the configuration file under the device management rules directory of the operating system, and a check is performed to see if there are any conflicting rules before writing. The system invokes the device management commands provided by the operating system to reload all the device permission rules and trigger device events, so that the new rules take effect immediately. At the same time, it verifies whether the permissions are successfully applied by re-enumerating the devices and persists the successfully authorized printer information to the local configuration file so that the saved permission configuration can be applied when the system starts up or the device is plugged in or unplugged.

3. The method according to claim 1, characterized in that, The method further includes: Based on the priority field in the JSON format print instruction, the print task is inserted into the corresponding position in the concurrent queue to realize the queue-jumping processing of high-priority tasks; After successfully adding the print job to the concurrent queue, if the receipt flag is true, the WebSocket server returns a confirmation message to the client containing the job ID and the estimated waiting time for the current queue position. If an event occurs during the execution of the printing task that allows for progress feedback, an intermediate status update containing the task ID, execution progress percentage, and remaining estimated time will be pushed to the client via the WebSocket server. After the printing task is completed or fails, a final status report containing the task ID, execution result, time consumption statistics and detailed error codes is generated and asynchronously pushed to the client through the WebSocket server.

4. The method according to claim 1, characterized in that, The step of drawing text, barcodes, or images on the virtual canvas according to the content drawing instructions, and calling a cross-platform graphics rendering library to generate image data to be printed, specifically includes: Based on the canvas parameters, initialize the memory canvas of the cross-platform graphics rendering library, and set the rendering resolution based on the DPI parameters of the target USB printer; According to the order of the content drawing instructions, the text, vector barcode and decoded image are rendered sequentially on the memory canvas to form a grayscale image; A preset edge enhancement algorithm is applied to the grayscale image to identify and sharpen the boundary regions between text and graphics in order to compensate for ink dot diffusion during the thermal printing process. For the edge-enhanced grayscale image, based on the physical characteristics of the thermal printhead of the target USB printer, a preset adaptive jitter algorithm is applied to dynamically adjust the jitter matrix parameters and generate a monochrome bitmap for the target USB printer. The monochrome bitmap is segmented according to the minimum print line unit of the target USB printer and encapsulated into a raster bitmap printing instruction stream conforming to the native protocol.

5. The method according to claim 4, characterized in that, The step of dynamically adjusting the dithering matrix parameters by applying a preset adaptive dithering algorithm based on the physical characteristics of the thermal printhead of the target USB printer to generate a monochrome bitmap for the target USB printer specifically includes: The physical characteristic parameters of the thermal printhead of the target USB printer are obtained, including printhead resolution, heating dot density, single-point heating time curve, and thermal diffusivity of adjacent heating points. Based on the thermal diffusivity, a thermal diffusivity model is constructed to predict the range of heat impact of each printing point on adjacent pixels during the printing process; Based on the aforementioned thermal diffusion model, pre-compensation calculations are performed on each pixel in the monochrome bitmap, and the heating intensity of the current pixel is dynamically adjusted according to the printing status of adjacent pixels to counteract the blurring effect caused by thermal diffusion. Based on the historical printing data of the target USB printer, the optimal jitter matrix parameters under different ambient temperatures are statistically analyzed, and a mapping relationship between ambient temperature and jitter matrix parameters is established. During the printing process, the current ambient temperature is collected in real time, and a matching dithering matrix is ​​dynamically selected according to the mapping relationship to perform halftone processing on the monochrome bitmap and generate the final monochrome bitmap.

6. The method according to claim 1, characterized in that, The step of processing the print tasks in the concurrent queue sequentially through the print daemon includes: After retrieving a print job from the concurrent queue, a pre-print diagnostic command is sent to the target USB printer through the user-mode USB communication library. The pre-print diagnostic command includes a comprehensive query of the printer's internal buffer status, printhead temperature, and remaining paper level. Receive and parse the diagnostic response data of the target USB printer in response to the pre-print diagnostic command, and establish the state vector of the target USB printer; The state vector is input into a preset expert rule engine, which determines whether the current state is suitable for continuing printing based on a historical fault mode library, and predicts the possible fault types. If it is determined that printing is not suitable or a high-risk failure is predicted, the corresponding processing strategy is executed according to the output of the rule engine, including pausing the current queue or putting the task back to the head of the queue and marking it as requiring manual intervention. If the printer is deemed suitable for printing, the printing task will continue, and the printer's real-time status feedback will be continuously monitored during the printing process.

7. The method according to claim 1, characterized in that, The method further includes: The user-space USB communication library enumerates all connected USB printers, creates a device object for each USB printer, and collects performance parameters, including maximum printing speed, resolution, current number of tasks, and historical failure rate. Based on the collected performance parameters, a real-time load weight is dynamically calculated for each printer, and a consistent hash ring is constructed based on the real-time load weight for task routing decisions. The set of candidate printers that meet the printing conditions is selected by matching the print quality requirement field in the JSON format print command with the performance parameters of each USB printer. For each print job to be processed, the optimal target USB printer is selected by consistent hashing algorithm based on the hash value of the job identifier and the real-time load weight of the candidate printers, and the job is routed to the concurrent queue dedicated to the target USB printer. When processing each concurrent queue, the real-time load and task completion status of each USB printer are continuously monitored, the real-time load weight is dynamically adjusted and the consistent hash ring is updated to achieve adaptive load balancing among multiple printers.

8. A computer system comprising a memory, a processor, and a computer program stored in the memory, characterized in that, The processor executes the computer program to implement the steps of the method according to any one of claims 1-7.

9. A computer-readable storage medium having a computer program / instructions stored thereon, characterized in that, When the computer program / instructions are executed by the processor, they implement the steps of the method described in any one of claims 1-7.

10. A computer program product comprising a computer program / instructions, characterized in that, When the computer program / instructions are executed by the processor, they implement the steps of the method described in any one of claims 1-7.