src/ptouch.c

Wed, 05 Aug 2009 15:15:47 +0100

author
Philip Pemberton <philpem@philpem.me.uk>
date
Wed, 05 Aug 2009 15:15:47 +0100
changeset 15
e5577dd259c6
parent 14
088286f9e1e4
child 19
b7fe751ea60d
permissions
-rw-r--r--

multiple fixes -- now prints successfully to a PT-2450DX.
FIX: job options were being set in GetStatus, now moved to their rightful home in Initialise()
REFACTOR: small mods to structure of Initialise, now uses PT_ERR_* consts, calls pt_Close on failure, exit logic slightly changed.
FIX: debug options should NOT have been set in Hg source (especially SKIP_STATUS_READBACK), now fixed.

     1 /****************************************************************************
     2  * Project:   P-touch printer driver library
     3  * Developer: Philip Pemberton
     4  * Purpose:   Make Brother P-touch (PT-series) printers do something besides
     5  *            gather dust.
     6  *
     7  *            Currently supports:
     8  *              PT-2450DX
     9  ****************************************************************************/
    11 // TODO: disable
    12 //#define DEBUG
    14 // This debug option forces Request Status to always "see" a good status
    15 // block. Mostly useful for testing using write-to-file mode.
    16 //#define DEBUG_SKIP_STATUS_READ
    18 #include <stdio.h>
    19 #include <stdlib.h>
    20 #include <stdbool.h>
    21 #include <string.h>
    22 #include <gd.h>
    23 #include "hexdump.h"
    24 #include "ptouch.h"
    26 #define ESC 0x1b
    28 pt_Device *pt_Initialise(char *path)
    29 {
    30 	pt_Device	*dev;
    31 	FILE		*prn;
    33 	// Try and open the printer device
    34 	prn = fopen(path, "r+b");
    35 	if (prn == NULL) {
    36 		return NULL;
    37 	}
    39 	// Printer device open, send an init command and read the status
    40 	fprintf(prn, "%c%c", ESC, '@');
    42 	// Allocate memory for the device block
    43 	dev = malloc(sizeof(pt_Device));
    44 	if (dev == NULL) {
    45 		fclose(prn);
    46 		return NULL;
    47 	}
    49 	// Store the file pointer
    50 	dev->fp = prn;
    52 	// Memory allocation OK, now get the printer's status
    53 	if (pt_GetStatus(dev) != PT_ERR_SUCCESS) {
    54 		// GetStatus failed, close the device and exit.
    55 		pt_Close(dev);
    56 		return NULL;
    57 	}
    59 	// Set printing parameters to defaults --
    60 	//   Mirror off
    61 	//   Autocut off
    62 	dev->mirror = false;
    63 	dev->autocut = false;
    65 	return dev;
    66 }
    68 int pt_GetStatus(pt_Device *dev)
    69 {
    70 #ifdef DEBUG_SKIP_STATUS_READ
    71 	unsigned char buf[32];
    72 	memset(buf, 0x00, 32);
    73 	buf[0] = 0x80;
    74 	buf[1] = 0x20;
    75 	buf[2] = 0x42;
    76 	buf[3] = 0x30;
    77 	buf[4] = 0x4b;
    78 	buf[5] = 0x30;
    79 	buf[10] = 0x0c;
    80 	buf[11] = 0x01;
    81 #else
    82 	// REQUEST STATUS
    83 	fprintf(dev->fp, "%c%c%c", ESC, 'i', 'S');
    85 	// Read status buffer from printer
    86 	unsigned char buf[32];
    87 	int timeout = 128;
    88 	do {
    89 		fread(buf, 1, 32, dev->fp);
    90 	} while ((buf[0] != 0x80) && (timeout-- > 0));
    92 	// Check for timeout
    93 	if (timeout == 0) {
    94 		// Timeout
    95 		return PT_ERR_TIMEOUT;
    96 	}
    97 #endif
    99 #ifdef DEBUG
   100 	printf("DEBUG: Printer status buffer = \n");
   101 	hex_dump(buf, 32);
   102 #endif
   104 	// Decode the status buffer, store the results in the device object
   105 	dev->errorInfo[0] = buf[8];
   106 	dev->errorInfo[1] = buf[9];
   107 	dev->mediaWidth   = buf[10];
   108 	dev->mediaType    = buf[11];
   109 	dev->mediaLength  = buf[17];
   110 	dev->statusType   = buf[18];
   111 	dev->phaseType    = buf[19];
   112 	dev->phaseHi      = buf[20];
   113 	dev->phaseLo      = buf[21];
   114 	dev->notification = buf[22];
   116 	// Set pixel width (label width in pixels)
   117 	if (dev->mediaWidth >= 24) {
   118 		// Label tape is 24mm or wider. Print head is 128 dots at 180dpi,
   119 		// which is 18.06mm. Thus, we can only print on the centre 18mm
   120 		// of a tape that is wider than 18mm.
   121 		dev->pixelWidth = 128;
   122 	} else {
   123 		// Print head is 180dpi. Pixel size is mediaWidth * dpi. If we
   124 		// multiply by ten, then divide by 254, we can avoid using
   125 		// floating point to convert from inches to mm. The -2 is a
   126 		// safety margin -- one pixel on either side of the label.
   127 		// This is far closer than Brother suggest, but hey-ho.
   128 		dev->pixelWidth = ((dev->mediaWidth * 180 * 10) / 254) - 2;
   129 	}
   131 	// Operation succeeded
   132 	return PT_ERR_SUCCESS;
   133 }
   135 int pt_SetOption(pt_Device *dev, PT_E_OPTION option, int value)
   136 {
   137 	// trap dev == NULL
   138 	if (dev == NULL) {
   139 		return PT_ERR_BAD_PARAMETER;
   140 	}
   142 	// set option
   143 	switch(option) {
   144 		case PT_OPTION_MIRROR:			// Mirror
   145 			dev->mirror = (value ? 1 : 0);
   146 			return PT_ERR_SUCCESS;
   148 		case PT_OPTION_AUTOCUT:		// Auto-cutter enable/disable
   149 			dev->autocut = (value ? 1 : 0);
   150 			return PT_ERR_SUCCESS;
   152 		default:
   153 			return PT_ERR_BAD_PARAMETER;
   154 	}
   155 }
   157 int pt_GetOption(pt_Device *dev, PT_E_OPTION option, int *value)
   158 {
   159 	// trap dev == NULL or value == NULL
   160 	if ((dev == NULL) || (value == NULL)) {
   161 		return PT_ERR_BAD_PARAMETER;
   162 	}
   164 	// get option value
   165 	switch(option) {
   166 		case PT_OPTION_MIRROR:			// Mirror
   167 			*value = dev->mirror;
   168 			return PT_ERR_SUCCESS;
   170 		case PT_OPTION_AUTOCUT:		// Auto-cutter enable/disable
   171 			*value = dev->autocut;
   172 			return PT_ERR_SUCCESS;
   174 		default:
   175 			return PT_ERR_BAD_PARAMETER;
   176 	}
   177 }
   179 int pt_Print(pt_Device *dev, gdImagePtr *labels, int count)
   180 {
   181 	int err;
   182 	gdImagePtr *curLabel = labels;
   184 	// trap dev == NULL
   185 	if (dev == NULL) {
   186 		return PT_ERR_BAD_PARAMETER;
   187 	}
   189 	// trap labels == NULL
   190 	if (labels == NULL) {
   191 		return PT_ERR_BAD_PARAMETER;
   192 	}
   194 	// trap count == 0
   195 	if (count == 0) {
   196 		return PT_ERR_BAD_PARAMETER;
   197 	}
   199 	// Request current status from the printer
   200 	if ((err = pt_GetStatus(dev)) != PT_ERR_SUCCESS) {
   201 		return err;
   202 	}
   204 	// Make sure the printer has tape, and is ready
   205 	if ((dev->errorInfo[0] != 0x00) || (dev->errorInfo[1] != 0x00)) {
   206 		return PT_ERR_PRINTER_NOT_READY;
   207 	}
   209 	// Send the print initialisation commands
   210 	//
   211 	// ESC i M -- Set Mode
   212 	fprintf(dev->fp, "%ciM%c", ESC,
   213 			(dev->autocut ? 0x40 : 0x00) | (dev->mirror ? 0x80 : 0x00));
   215 	// ESC i K -- Set Expanded Mode
   216 	fprintf(dev->fp, "%ciK%c", ESC, 0x00);
   218 	// ESC i R {n1} -- Set Raster Graphics Transfer Mode
   219 	//   {n1} = 0x01 ==> Raster Graphics mode
   220 	fprintf(dev->fp, "%ciR%c", ESC, 0x01);
   222 	// M {n1} -- Set Compression Mode
   223 	//   {n1} = 0x00 ==> no compression
   224 	//   	Doesn't seem to work on the PT-2450DX...
   225 	//   {n1} = 0x01 ==> reserved
   226 	//   {n1} = 0x02 ==> TIFF/Packbits
   227 	//   	But this works fine on the PT-2450DX...
   228 	fprintf(dev->fp, "M%c", 0x02);
   230 	// Loop over the images that were passed in
   231 	for (int imnum=0; imnum < count; imnum++) {
   232 		// Make sure image is the right size for this label tape
   233 		if (gdImageSY(*curLabel) != dev->pixelWidth) {
   234 			return PT_ERR_LABEL_TOO_WIDE;
   235 		}
   237 		// Trap a label with a width of zero
   238 		// I'm not sure if this can happen, but it's a single if statement, so
   239 		// probably worth checking anyway...
   240 		if (gdImageSX(*curLabel) == 0) {
   241 			return PT_ERR_LABEL_ZERO_LENGTH;
   242 		}
   244 		// Get the index of the colour "white" (RGB:255,255,255) in the Gd image
   245 		int col_white = gdImageColorResolve(*curLabel, 255, 255, 255);
   247 		// Iterate left-to-right over the source image
   248 		for (int xpos = 0; xpos < gdImageSX(*curLabel); xpos++) {
   249 			char bitbuf[128/8];		// 128-dot printhead, 8 bits per byte
   250 			int rowclear = true;	// TRUE if entire row is clear, else FALSE
   252 			// Fill bit buffer with zeroes
   253 			memset(bitbuf, 0x00, sizeof(bitbuf));
   255 			// Calculate left-side margin for this label size
   256 			// Again, 128-dot printhead.
   257 			int margin = (128 / 2) - (dev->pixelWidth / 2);
   259 			// Copy data from the image to the bit-buffer
   260 			for (int ypos = 0; ypos < gdImageSY(*curLabel); ypos++) {
   261 				// Get pixel from gd, is it white?
   262 				if (gdImageGetPixel(*curLabel, xpos, ypos) != col_white) {
   263 					// No. Set the bit.
   264 					int bit = 1 << (7 - ((margin+ypos) % 8));
   265 					bitbuf[(margin+ypos) / 8] |= bit;
   267 					// Clear the "row is clear" flag
   268 					rowclear = false;
   269 				}
   270 			}
   272 			// We now have the image data in bitbuf, and a flag to say whether
   273 			// there are any black pixels in the buffer. We can pack full-rows
   274 			// by sending a "Z" character, i.e. "this row is entirely blank".
   275 			// If not, we have to send a (128/8)=16 byte chunk of image data.
   276 			if (rowclear) {
   277 				// Row is clear -- send a "clear row" command
   278 				fprintf(dev->fp, "Z");
   279 			} else {
   280 				// Row is not clear -- send the pixel data
   281 				//
   282 				// TODO: the printer supports Packbits compression. Implement!
   283 				// TODO: After Packbits is implemented, ((128/8)+1) must be
   284 				//   changed to the length of the Packbits compressed data.
   285 				//   (note: 128/8 is the printhead size in bytes, the +1 is for
   286 				//   the control byte we add below...)
   287 				fprintf(dev->fp, "G%c%c", ((128/8)+1) & 0xff, ((128/8)+1) >> 8);
   289 				// This printer asks for Packbits compressed data. In this
   290 				// case, we send a "run of N" control byte and fake it...
   291 				fputc(sizeof(bitbuf) - 1, dev->fp);
   292 				for (int i=0; i<sizeof(bitbuf); i++) {
   293 					fputc(bitbuf[i], dev->fp);
   294 				}
   295 			}
   296 		}
   298 		// Is this the last label?
   299 		if (imnum == (count-1)) {
   300 			// Yes, send an End Job command
   301 			fprintf(dev->fp, "%c", 0x1A);
   302 		} else {
   303 			// No, more labels to print. Send a formfeed.
   304 			fprintf(dev->fp, "%c", 0x0C);
   305 		}
   307 		// Move onto the next label
   308 		curLabel++;
   309 	}
   311 	// Operation successful.
   312 	return PT_ERR_SUCCESS;
   313 }
   315 void pt_Close(pt_Device *dev)
   316 {
   317 	// Sanity check -- make sure dev is not null
   318 	if (dev == NULL) return;
   320 	// Close the printer stream
   321 	fclose(dev->fp);
   323 	// Release the memory allocated to the status buffer
   324 	free(dev);
   325 }