Source

epilog / live-laser.c

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
/** \file
 * Live laser test.
 *
 * HPGL spec: http://www.piclist.com/techref/language/hpgl/commands.htm
 *
 * Normal commands:
 * PD[x1,y1[,x2,y2...]]; -- pen down and list of coordinates
 * PU[x1,y1[,x2,y2...]]; -- pen up and list of coordinates
 *
 * Special commands:
 * XR == vector frequency
 * YP == vectory power
 * ZS == vector speed
 *
 */
/*
 * Copyright 2011 Trammell Hudson <hudson@osresearch.net>
 *
 * Portions
 * Copyright © 2002-2008 Andrews & Arnold Ltd <info@aaisp.net.uk>
 * Copyright 2008 AS220 Labs <brandon@as220.org>
 * Copyright 2011 Trammell Hudson <hudson@osresearch.net>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *========================================================================
 */
#include <ctype.h>
#include <errno.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <sys/signal.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <getopt.h>
#include <pwd.h>
#include <cv.h>
#include <highgui.h>

static int vector_power = 100;
static int vector_speed = 50;
static int update_param;


typedef struct
{
	int fd;
	const char * host;
	const char * title;
	const char * queue;
	const char * user;
	const char * job_name;
	size_t job_size;
	int auto_focus;
	uint32_t resolution;
	uint32_t width;
	uint32_t height;
	size_t sent_bytes;
} printer_job_t;


void
printer_send_raw(
	printer_job_t * const job,
	const void * const buf,
	const size_t len
)
{
#if 0
	unsigned i;
	fprintf(stderr, "sending %zu bytes:", len);
	for(i = 0 ; i < len ; i++)
	{
		char c = buf[i];
		fprintf(stderr, "%c", isprint(c) ? c : '.');
	}

	for(i = 0 ; i < len ; i++)
		fprintf(stderr, " %02x", (uint8_t) buf[i]);
	fprintf(stderr, "\n");
#else
	//write(1, buf, len);
#endif
	if (job->sent_bytes > job->job_size - 64)
	{
		fprintf(stderr, "Too many bytes!  We're done\n");
		return;
	}

	// epilog.c sends the nul at the end?
	ssize_t rc = write(job->fd, buf, len);
	if (rc != (ssize_t) len)
	{
		perror("short write");
		abort();
	}

	job->sent_bytes += len;
}


void
printer_send(
	printer_job_t * const job,
	const char * const fmt,
	...
)
{
	static char buf[1024];
	va_list ap;
	va_start(ap, fmt);
	ssize_t len = vsnprintf(buf, sizeof(buf), fmt, ap);
	va_end(ap);

	printer_send_raw(job, buf, len);
}


void
vector_moveto(
	printer_job_t * const job,
	int pen,
	uint32_t x,
	uint32_t y
)
{
	printer_send(job, "P%c%d,%d;",
		pen ? 'D' : 'U',
		x,
		y
	);
}


void
vector_param(
	printer_job_t * const job,
	int freq,
	int power,
	int speed
)
{
	fprintf(stderr, "Hz=%d Power=%d Speed=%d\n", freq, power, speed);

	printer_send(job,
		"XR%04d;YP%03d;ZS%03d;",
		freq,
		power,
		speed
	);
}


void
vector_init(
	printer_job_t * const job
)
{
	/* add vector information to the print job. */
        printer_send(job, "\eE@PJL ENTER LANGUAGE=PCL\r\n");

        /* Page Orientation */
        printer_send(job, "\e*r0F");
        printer_send(job, "\e*r%dT", job->height);
        printer_send(job, "\e*r%dS", job->width);
        printer_send(job, "\e*r1A");
        printer_send(job, "\e*rC");
        printer_send(job, "\e%%1B");

	// We are now in HPGL mode 
	printer_send(job, "IN;");
}


void
vector_end(
	printer_job_t * const job
)
{
	printer_send(job, "\e%%0B"); // end HLGL
	printer_send(job, "\e%%1BPU");  // start HLGL, and pen up, end
}



/** vector doesn't work without a fake raster component */
static void
raster_header(
	printer_job_t * const job
)
{
	/* Unknown purpose */
	printer_send(job, "\e&y0C");
        /* Raster Orientation */
        printer_send(job, "\e*r0F");
        /* Raster power */
        printer_send(job, "\e&y%dP", 100);

        /* Raster speed */
        printer_send(job, "\e&z%dS", 100);
        printer_send(job, "\e*r%dT", job->height);
        printer_send(job, "\e*r%dS", job->width);

        /* Raster compression */
/*
        fprintf(pjl_file, "\e*b%dM", (raster_mode == 'c' || raster_mode == 'g')
                ? 7 : 2);
*/
	printer_send(job, "\e*b7M");

        /* Raster direction (1 = up) */
        printer_send(job, "\e&y1O");
}

static void
raster_footer(
	printer_job_t * const job
)
{
        printer_send(job, "\e*rC%c%c",
		(char) 26,
		(char) 4
	);
}


/**
 *
 */
static void
printer_header(
	printer_job_t * const job
)
{
    /* Print the printer job language header. */
    printer_send(job, "\e%%-12345X@PJL JOB NAME=%s\r\n", job->title);
    printer_send(job, "\eE@PJL ENTER LANGUAGE=PCL\r\n");
    /* Set autofocus on or off. */
    printer_send(job, "\e&y%dA", job->auto_focus);
    /* Left (long-edge) offset registration.  Adjusts the position of the
     * logical page across the width of the page.
     */
    printer_send(job, "\e&l0U");
    /* Top (short-edge) offset registration.  Adjusts the position of the
     * logical page across the length of the page.
     */
    printer_send(job, "\e&l0Z");

    /* Resolution of the print. */
    printer_send(job, "\e&u%dD", job->resolution);
    /* X position = 0 */
    printer_send(job, "\e*p0X");
    /* Y position = 0 */
    printer_send(job, "\e*p0Y");
    /* PCL resolution. */
    printer_send(job, "\e*t%dR", job->resolution);

	// vector only mode still requires an empty raster section
	raster_header(job);
	raster_footer(job);

#if 0
    /* If raster power is enabled and raster mode is not 'n' then add that
     * information to the print job.
     */
    if (raster_power && raster_mode != 'n') {

        /* FIXME unknown purpose. */
        printer_send(job, "\e&y0C");

        /* We're going to perform a raster print. */
        generate_raster(pjl_file, bitmap_file);
    }
#endif

}


/** Send footer for printer job language.
 */
static void
printer_footer(
	printer_job_t * const job
)
{
	/* Reset */
	printer_send(job, "\eE");
	/* Exit language and end job. */
	printer_send(job, "\e%%-12345X@PJL EOJ \r\n");

	fprintf(stderr, "sent %zu bytes / %zu\n", job->sent_bytes, job->job_size);

	/* Pad out the remainder of the file with 0 characters. */
	size_t i;
	size_t remaining = job->job_size - job->sent_bytes;
	fprintf(stderr, "sending %zu pad bytes\n", remaining);
	job->sent_bytes = 0;

	void * buf = calloc(1, remaining + 4096);
	printer_send_raw(job, buf, remaining + 4096);
}


/**
 * Connect to a printer.
 *
 * @param host The hostname or IP address of the printer to connect to.
 * @param timeout The number of seconds to wait before timing out on the
 * connect operation.
 * @return A socket descriptor to the printer.
 */
static int
tcp_connect(const char *host, const int timeout)
{
	int i;

	for (i = 0; i < timeout; i++)
	{
		struct addrinfo *res;
		struct addrinfo *addr;
		struct addrinfo base = {
			.ai_family	= PF_UNSPEC,
			.ai_socktype	= SOCK_STREAM,
		};
		int error_code = getaddrinfo(host, "printer", &base, &res);

		/* Set an alarm to go off if the program has gone out to lunch. */
		alarm(10);

		/* If getaddrinfo did not return an error code then we attempt to
		 * connect to the printer and establish a socket.
		 */
		if (error_code)
		{
			/* Sleep for a second then try again. */
			sleep(1);
			continue;
		}

		for (addr = res; addr; addr = addr->ai_next)
		{
			const struct sockaddr_in * addr_in
				= (void*) addr->ai_addr;

			if (!addr_in)
				continue;

			fprintf(stderr,
				"trying to connect to %s:%d\n",
				inet_ntoa(addr_in->sin_addr),
				ntohs(addr_in->sin_port)
		       );

			const int fd = socket(
				addr->ai_family,
				addr->ai_socktype,
				addr->ai_protocol
			);

			if (fd < 0)
				continue;

			int rc = connect(
				fd,
				addr->ai_addr,
				addr->ai_addrlen
			);

			if (rc < 0)
			{
				close(fd);
				continue;
			}

			// Found it and connected
			alarm(0);
			freeaddrinfo(res);
			return fd;
		}

		// Didn't find anything this time; try again
		freeaddrinfo(res);
	}

	fprintf(stderr, "Cannot connect to %s\n", host);
	alarm(0);
	return -1;
}


/**
 * Disconnect from a printer.
 *
 * @param socket_descriptor the descriptor of the printer that is to be
 * disconnected from.
 * @return True if the printer connection was successfully closed, false otherwise.
 */
static bool
tcp_disconnect(int fd)
{
	fprintf(stderr, "closing socket\n");
	int rc = close(fd);
	if (rc == 0)
		return true;

	perror("close failed");
	return false;
}


static void
printer_disconnect(
	printer_job_t * const job
)
{
	tcp_disconnect(job->fd);
	free(job);
}


static int
printer_read(
	printer_job_t * const job
)
{
	// ensure that all output has been sent
	fprintf(stderr, "waiting on fd %d\n", job->fd);
	int8_t result = -1;
	ssize_t rc = read(job->fd, &result, sizeof(result));

	fprintf(stderr, "rc=%zd value=%d\n", rc, result);

	// Success == 0 byte
	if (rc == sizeof(result) && result == 0)
		return 1;

	if (rc != sizeof(result))
		perror("printer read failed");
	else
		fprintf(stderr, "printer returned failure code %02x\n", result);

	return 0;
}


/**
 *
 */
static printer_job_t *
printer_connect(
	const char * const host
)
{
	printer_job_t * const job = calloc(1, sizeof(*job));
	if (!job)
		return NULL;

	const uint32_t dpi = 150;

	*job = (printer_job_t) {
		.host		= strdup(host),
		.job_name	= "live.pdf",
		.job_size	= 64 << 10, // fake 64 MB for now
		.title		= "live-test",
		.queue		= "",
		.user		= "user",
		.auto_focus	= 0,
		.resolution	= dpi,
		.width		= 8 * dpi,
		.height		= 8 * dpi,
	};

	char localhost[128] = "";

	gethostname(localhost, sizeof(localhost));
	char *d = strchr(localhost, '.');
	if (d)
	    *d = 0;

	/* Connect to the printer. */
	job->fd = tcp_connect(job->host, 60);
	if (job->fd < 0)
		return NULL;

	// talk to printer
	printer_send(job, "\002%s\n", job->queue);
	if (!printer_read(job))
		return NULL;

/*
	// due to off-by-one errors, the epilog.c code never sends these
	printer_send(job, "P%s\n", job->user);
	printer_send(job, "J%s\n", job->title);
	printer_send(job, "ldfA%s:%s\n", job->job_name, localhost);
	printer_send(job, "UdfA%s:%s\n", job->job_name, localhost);
	printer_send(job, "N%s\n", job->title);
*/
	printer_send(job, "\002%zu cfA%s%s\n",
		strlen(localhost) + 2, // the length of the H command
		job->job_name,
		localhost
	);
	if (!printer_read(job))
		return NULL;

	printer_send(job, "H%s\n", localhost);
	char nul = '\0';
	printer_send_raw(job, &nul, 1);
	if (!printer_read(job))
		return NULL;

	printer_send(job, "\003%zu dfA%s%s\n",
		job->job_size,
		job->job_name,
		localhost
	);
	if (!printer_read(job))
		return NULL;

	job->sent_bytes = 0;
	return job;
}


static void
mouse_handler(
	int event,
	int x,
	int y,
	int flags,
	void * job_ptr
)
{
	static int last_down;

	printer_job_t * const job = job_ptr;

	if (update_param)
	{
		vector_param(job, 5000, vector_power, vector_speed);
		update_param = 0;
	}

	switch (event)
	{
	case CV_EVENT_MOUSEMOVE:
		if (flags & CV_EVENT_FLAG_CTRLKEY)
		{
			// If we're not already with the laser on,
			// do the first move with out firing.
			vector_moveto(job, last_down, x*2, y*2);
			last_down = 1;
			printf("%d, %d, %d\n", flags, x, y);
		} else
		if (last_down) {
			// Force a non-laser movement
			vector_moveto(job, 0, x*2, y*2);
			last_down = 0;
		}

		break;
	case CV_EVENT_LBUTTONDOWN:
		vector_moveto(job, 0, x*2, y*2);
		break;
	default:
		printf("event %d\n", event);
		break;
	}
}


static void
trackbar_callback(
	int unused
)
{
	(void) unused;
	update_param = 1;
}


int main(void)
{
#if 1
	printer_job_t _job;
	printer_job_t * const job = &_job;
#else
	printer_job_t * const job = printer_connect("192.168.3.4");
	if (!job)
		return -1;

	fprintf(stderr, "connected\n");

	printer_header(job);
	job->sent_bytes = 0;

	vector_init(job);
	vector_param(job, 5000, 100, 50);
#endif

	cvNamedWindow("main", CV_WINDOW_AUTOSIZE);
	IplImage * const img = cvCreateImage(cvSize(1024, 768), IPL_DEPTH_8U, 3);

	cvCreateTrackbar("power", "main", &vector_power, 100, trackbar_callback);
	cvCreateTrackbar("speed", "main", &vector_speed, 100, trackbar_callback);

	//cvSetMouseCallback("main", mouse_handler, job);
	cvShowImage("main", img);
	cvSetMouseCallback("main", mouse_handler, job);
	while (cvWaitKey(0) != 27)
		;
	
	vector_end(job);
	printer_footer(job);
	printer_disconnect(job);

	return 0;
}